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
a18941a0169d053800e7d7f63c413f2451bb120f
samples/auth_cb.adb
samples/auth_cb.adb
----------------------------------------------------------------------- -- auth_cb -- Authentication callback examples -- Copyright (C) 2013, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with AWS.Session; with AWS.Messages; with AWS.Templates; with AWS.Services.Web_Block.Registry; with Util.Log.Loggers; package body Auth_CB is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Auth_CB"); -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; USER_INFO_ATTRIBUTE : constant String := "user-info"; Null_Association : Security.Auth.Association; Null_Auth : Security.Auth.Authentication; package Auth_Session is new AWS.Session.Generic_Data (Security.Auth.Association, Null_Association); package User_Session is new AWS.Session.Generic_Data (Security.Auth.Authentication, Null_Auth); function Get_Auth_Name (Request : in AWS.Status.Data) return String; overriding function Get_Parameter (Params : in Auth_Config; Name : in String) return String is begin if Params.Exists (Name) then return Params.Get (Name); else return ""; end if; end Get_Parameter; function Get_Auth_Name (Request : in AWS.Status.Data) return String is URI : constant String := AWS.Status.URI (Request); Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "/", Ada.Strings.Backward); begin if Pos = 0 then return ""; else Log.Info ("OpenID authentication with {0}", URI); return URI (Pos + 1 .. URI'Last); end if; end Get_Auth_Name; -- ------------------------------ -- Implement the first step of authentication: discover the OpenID (if any) provider, -- create the authorization request and redirect the user to the authorization server. -- Some authorization data is saved in the session for the verify process. -- ------------------------------ function Get_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is Name : constant String := Get_Auth_Name (Request); URL : constant String := Config.Get_Parameter ("auth.url." & Name); Mgr : Security.Auth.Manager; OP : Security.Auth.End_Point; Assoc : Security.Auth.Association; begin if URL'Length = 0 or Name'Length = 0 then return AWS.Response.URL (Location => "/login.html"); end if; Mgr.Initialize (Config, Name); -- Yadis discovery (get the XRDS file). This step does nothing for OAuth. Mgr.Discover (URL, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc); SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Auth_Session.Set (SID, OPENID_ASSOC_ATTRIBUTE, Assoc); return AWS.Response.URL (Location => Auth_URL); end; end Get_Authorization; -- ------------------------------ -- Second step of authentication: verify the authorization response. The authorization -- data saved in the session is extracted and checked against the response. If it matches -- the response is verified to check if the authentication succeeded or not. -- The user is then redirected to the success page. -- ------------------------------ function Verify_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is use type Security.Auth.Auth_Result; -- Give access to the request parameters. type Auth_Params is limited new Security.Auth.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return AWS.Status.Parameter (Request, Name); end Get_Parameter; Mgr : Security.Auth.Manager; Assoc : Security.Auth.Association; Credential : Security.Auth.Authentication; Params : Auth_Params; SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Verify openid authentication"); if not AWS.Session.Exist (SID, OPENID_ASSOC_ATTRIBUTE) then Log.Warn ("Session has expired during OpenID authentication process"); return AWS.Response.Build ("text/html", "Session has expired", AWS.Messages.S403); end if; Assoc := Auth_Session.Get (SID, OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. AWS.Session.Remove (SID, OPENID_ASSOC_ATTRIBUTE); Mgr.Initialize (Name => Security.Auth.Get_Provider (Assoc), Params => Config); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc, Params, Credential); if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then Log.Info ("Authentication has failed"); return AWS.Response.Build ("text/html", "Authentication failed", AWS.Messages.S403); end if; Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Claimed id: {0}", Security.Auth.Get_Claimed_Id (Credential)); Log.Info ("Email: {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Name: {0}", Security.Auth.Get_Full_Name (Credential)); -- Save the user information in the session (for the purpose of this demo). User_Session.Set (SID, USER_INFO_ATTRIBUTE, Credential); declare URL : constant String := Config.Get_Parameter ("openid.success_url"); begin Log.Info ("Redirect user to success URL: {0}", URL); return AWS.Response.URL (Location => URL); end; end Verify_Authorization; function User_Info (Request : in AWS.Status.Data) return AWS.Response.Data is SID : constant AWS.Session.Id := AWS.Status.Session (Request); Credential : Security.Auth.Authentication; Set : AWS.Templates.Translate_Set; begin if AWS.Session.Exist (SID, USER_INFO_ATTRIBUTE) then Credential := User_Session.Get (SID, USER_INFO_ATTRIBUTE); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("ID", Security.Auth.Get_Claimed_Id (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("EMAIL", Security.Auth.Get_Email (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("NAME", Security.Auth.Get_Full_Name (Credential))); end if; return AWS.Services.Web_Block.Registry.Build ("success", Request, Set); end User_Info; end Auth_CB;
----------------------------------------------------------------------- -- auth_cb -- Authentication callback examples -- Copyright (C) 2013, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with AWS.Session; with AWS.Messages; with AWS.Templates; with AWS.Services.Web_Block.Registry; with Util.Log.Loggers; package body Auth_CB is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Auth_CB"); -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; USER_INFO_ATTRIBUTE : constant String := "user-info"; Null_Association : Security.Auth.Association; Null_Auth : Security.Auth.Authentication; package Auth_Session is new AWS.Session.Generic_Data (Security.Auth.Association, Null_Association); package User_Session is new AWS.Session.Generic_Data (Security.Auth.Authentication, Null_Auth); function Get_Auth_Name (Request : in AWS.Status.Data) return String; overriding function Get_Parameter (Params : in Auth_Config; Name : in String) return String is begin if Params.Exists (Name) then return Params.Get (Name); else return ""; end if; end Get_Parameter; function Get_Auth_Name (Request : in AWS.Status.Data) return String is URI : constant String := AWS.Status.URI (Request); Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "/", Ada.Strings.Backward); begin if Pos = 0 then return ""; else Log.Info ("OpenID authentication with {0}", URI); return URI (Pos + 1 .. URI'Last); end if; end Get_Auth_Name; -- ------------------------------ -- Implement the first step of authentication: discover the OpenID (if any) provider, -- create the authorization request and redirect the user to the authorization server. -- Some authorization data is saved in the session for the verify process. -- ------------------------------ function Get_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is Name : constant String := Get_Auth_Name (Request); URL : constant String := Config.Get_Parameter ("auth.url." & Name); Mgr : Security.Auth.Manager; OP : Security.Auth.End_Point; Assoc : Security.Auth.Association; begin if URL'Length = 0 or else Name'Length = 0 then return AWS.Response.URL (Location => "/login.html"); end if; Mgr.Initialize (Config, Name); -- Yadis discovery (get the XRDS file). This step does nothing for OAuth. Mgr.Discover (URL, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc); SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Auth_Session.Set (SID, OPENID_ASSOC_ATTRIBUTE, Assoc); return AWS.Response.URL (Location => Auth_URL); end; end Get_Authorization; -- ------------------------------ -- Second step of authentication: verify the authorization response. The authorization -- data saved in the session is extracted and checked against the response. If it matches -- the response is verified to check if the authentication succeeded or not. -- The user is then redirected to the success page. -- ------------------------------ function Verify_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is use type Security.Auth.Auth_Result; -- Give access to the request parameters. type Auth_Params is limited new Security.Auth.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return AWS.Status.Parameter (Request, Name); end Get_Parameter; Mgr : Security.Auth.Manager; Assoc : Security.Auth.Association; Credential : Security.Auth.Authentication; Params : Auth_Params; SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Verify openid authentication"); if not AWS.Session.Exist (SID, OPENID_ASSOC_ATTRIBUTE) then Log.Warn ("Session has expired during OpenID authentication process"); return AWS.Response.Build ("text/html", "Session has expired", AWS.Messages.S403); end if; Assoc := Auth_Session.Get (SID, OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. AWS.Session.Remove (SID, OPENID_ASSOC_ATTRIBUTE); Mgr.Initialize (Name => Security.Auth.Get_Provider (Assoc), Params => Config); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc, Params, Credential); if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then Log.Info ("Authentication has failed"); return AWS.Response.Build ("text/html", "Authentication failed", AWS.Messages.S403); end if; Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Claimed id: {0}", Security.Auth.Get_Claimed_Id (Credential)); Log.Info ("Email: {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Name: {0}", Security.Auth.Get_Full_Name (Credential)); -- Save the user information in the session (for the purpose of this demo). User_Session.Set (SID, USER_INFO_ATTRIBUTE, Credential); declare URL : constant String := Config.Get_Parameter ("openid.success_url"); begin Log.Info ("Redirect user to success URL: {0}", URL); return AWS.Response.URL (Location => URL); end; end Verify_Authorization; function User_Info (Request : in AWS.Status.Data) return AWS.Response.Data is SID : constant AWS.Session.Id := AWS.Status.Session (Request); Credential : Security.Auth.Authentication; Set : AWS.Templates.Translate_Set; begin if AWS.Session.Exist (SID, USER_INFO_ATTRIBUTE) then Credential := User_Session.Get (SID, USER_INFO_ATTRIBUTE); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("ID", Security.Auth.Get_Claimed_Id (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("EMAIL", Security.Auth.Get_Email (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("NAME", Security.Auth.Get_Full_Name (Credential))); end if; return AWS.Services.Web_Block.Registry.Build ("success", Request, Set); end User_Info; end Auth_CB;
Fix style warnings: add missing overriding and update and then/or else conditions
Fix style warnings: add missing overriding and update and then/or else conditions
Ada
apache-2.0
stcarrez/ada-security
c3b901a4e54e57b24f9003e9421a6386ffc35586
awa/src/awa-users-principals.ads
awa/src/awa-users-principals.ads
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- 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; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- 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; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.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; -- Utility functions based on the security principal access type. -- 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; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- 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; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- 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; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.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; -- Utility functions based on the security principal access type. -- 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; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; -- Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
Remove the Role_Map from the user principal
Remove the Role_Map from the user principal
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
66fe19307926c878a215fb5a26c59be998dbcf85
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)", Test_Input_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test input file redirection. -- ------------------------------ procedure Test_Input_Redirect (T : in out Test) is P : Process; In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-inres.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/expect/proc-inres.txt"); begin Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Spawn (P, "bin/util_test_process 0 read -"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Input_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)", Test_Input_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(CHDIR)", Test_Set_Working_Directory'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test input file redirection. -- ------------------------------ procedure Test_Input_Redirect (T : in out Test) is P : Process; In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/expect/proc-inres.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-inres.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "bin/util_test_process 0 read -"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Input_Redirect; -- ------------------------------ -- Test chaning working directory. -- ------------------------------ procedure Test_Set_Working_Directory (T : in out Test) is P : Process; Dir_Path : constant String := Util.Tests.Get_Path ("regtests/files"); In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-empty.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-cat.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Working_Directory (P, Dir_Path); Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "cat proc-input.txt"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Set_Working_Directory; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
Add the Test_Set_Working_Directory procedure and register it for execution (test launching a process with a specific working directory)
Add the Test_Set_Working_Directory procedure and register it for execution (test launching a process with a specific working directory)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cd50c51ab4b422febe291f0db60949272322f221
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.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;
----------------------------------------------------------------------- -- import -- Import some HTML content and generate Wiki text -- 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.Text_IO; with Ada.Wide_Wide_Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with GNAT.Command_Line; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings.Transforms; with Wiki.Strings; 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; use Ada.Strings.UTF_Encoding; procedure Usage; function Is_Url (Name : in String) return Boolean; procedure Parse_Url (Url : in String); procedure Parse (Content : in String); procedure Print (Item : in Wiki.Strings.WString); 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 Print (Item : in Wiki.Strings.WString) is begin Ada.Wide_Wide_Text_IO.Put (Item); end Print; 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 (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access, Syntax); Renderer.Render (Doc); Stream.Iterate (Print'Access); 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 (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); 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 (Wide_Wide_Strings.Decode (Content), Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Print'Access); end; end if; Ada.Wide_Wide_Text_IO.New_Line; 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;
Fix conversion of String to Wide_Wide_String so that we recognized UTF-8 sequences
Fix conversion of String to Wide_Wide_String so that we recognized UTF-8 sequences
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
49fbe629518a0e118c952b460b34002f61518fb4
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Filter_Type) is begin Document.Document.Finish; end Finish; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type) is begin if Filter.Next /= null then Filter.Next.Finish; end if; end Finish; end Wiki.Filters;
Fix the filter chain execution
Fix the filter chain execution
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
47bfaef28e1555d085878e96e9f069406073e760
src/util-concurrent-pools.ads
src/util-concurrent-pools.ads
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which -- can be shared by multiple threads. First, the pool is configured to have -- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread -- that needs an object uses the <b>Get_Instance</b> to get an object. -- The object is removed from the pool. As soon as the thread has finished, -- it puts back the object in the pool using the <b>Release</b> procedure. -- -- The <b>Get_Instance</b> entry will block until an object is available. generic type Element_Type is private; package Util.Concurrent.Pools is pragma Preelaborate; -- Pool of objects type Pool is new Ada.Finalization.Limited_Controlled with private; -- Get an element instance from the pool. -- Wait until one instance gets available. procedure Get_Instance (From : in out Pool; Item : out Element_Type); -- Put the element back to the pool. procedure Release (Into : in out Pool; Item : in Element_Type); -- Set the pool size. procedure Set_Size (Into : in out Pool; Capacity : in Positive); -- Release the pool elements. overriding procedure Finalize (Object : in out Pool); private -- To store the pool elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Pool of objects protected type Protected_Pool is -- Get an element instance from the pool. -- Wait until one instance gets available. entry Get_Instance (Item : out Element_Type); -- Put the element back to the pool. procedure Release (Item : in Element_Type); -- Set the pool size. procedure Set_Size (Capacity : in Natural); private Available : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Pool; type Pool is new Ada.Finalization.Limited_Controlled with record List : Protected_Pool; end record; end Util.Concurrent.Pools;
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>Util.Concurrent.Pools</b> generic defines a pool of objects which -- can be shared by multiple threads. First, the pool is configured to have -- a number of objects by using the <b>Set_Size</b> procedure. Then, a thread -- that needs an object uses the <b>Get_Instance</b> to get an object. -- The object is removed from the pool. As soon as the thread has finished, -- it puts back the object in the pool using the <b>Release</b> procedure. -- -- The <b>Get_Instance</b> entry will block until an object is available. generic type Element_Type is private; package Util.Concurrent.Pools is pragma Preelaborate; FOREVER : constant Duration := -1.0; -- Exception raised if the Get_Instance timeout exceeded. Timeout : exception; -- Pool of objects type Pool is limited new Ada.Finalization.Limited_Controlled with private; -- Get an element instance from the pool. -- Wait until one instance gets available. procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER); -- Put the element back to the pool. procedure Release (Into : in out Pool; Item : in Element_Type); -- Set the pool size. procedure Set_Size (Into : in out Pool; Capacity : in Positive); -- Release the pool elements. overriding procedure Finalize (Object : in out Pool); private -- To store the pool elements, we use an array which is allocated dynamically -- by the <b>Set_Size</b> protected operation. The generated code is smaller -- compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; -- Pool of objects protected type Protected_Pool is -- Get an element instance from the pool. -- Wait until one instance gets available. entry Get_Instance (Item : out Element_Type); -- Put the element back to the pool. procedure Release (Item : in Element_Type); -- Set the pool size. procedure Set_Size (Capacity : in Natural); private Available : Natural := 0; Elements : Element_Array_Access := Null_Element_Array; end Protected_Pool; type Pool is limited new Ada.Finalization.Limited_Controlled with record List : Protected_Pool; end record; end Util.Concurrent.Pools;
Add a timeout for the Get_Instance operation to raise the timeout exception if the delay is expired and no item from the pool was available
Add a timeout for the Get_Instance operation to raise the timeout exception if the delay is expired and no item from the pool was available
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
45db10a5cde6f4c7387795046b3258498895a4c6
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 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.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object (""); end if; Handler.Sink.Start_Object (""); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; -- Context : Element_Context_Access; begin -- Context_Stack.Push (Handler.Stack); -- Context := Context_Stack.Current (Handler.Stack); -- Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; Handler.Sink := null; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); -- Context_Stack.Pop (Handler.Stack); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 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.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object (""); else Handler.Sink.Start_Array (""); end if; Handler.Sink.Start_Object (""); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; -- Context : Element_Context_Access; begin -- Context_Stack.Push (Handler.Stack); -- Context := Context_Stack.Current (Handler.Stack); -- Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; Handler.Sink := null; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); -- Context_Stack.Pop (Handler.Stack); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Call the Start_Array for the first row of the CSV file (excluding the header)
Call the Start_Array for the first row of the CSV file (excluding the header)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
51653ecf5dda508bfe7bf45b24b04eb3a72946f3
regtests/asf-contexts-faces-tests.ads
regtests/asf-contexts-faces-tests.ads
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with EL.Contexts.Default; with EL.Variables; with ASF.Tests; with ASF.Applications.Tests; with ASF.Helpers.Beans; package ASF.Contexts.Faces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); function Get_Form_Bean is new ASF.Helpers.Beans.Get_Bean (ASF.Applications.Tests.Form_Bean, ASF.Applications.Tests.Form_Bean_Access); type Test is new ASF.Tests.EL_Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. Form : ASF.Applications.Tests.Form_Bean_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out Test); -- Setup the faces context for the unit test. procedure Setup (T : in out Test; Context : in out Faces_Context); -- Test getting an attribute from the faces context. procedure Test_Get_Attribute (T : in out Test); -- Test getting a bean object from the faces context. procedure Test_Get_Bean (T : in out Test); -- Test getting a bean object from the faces context and doing a conversion. procedure Test_Get_Bean_Helper (T : in out Test); -- Test the faces message queue. procedure Test_Add_Message (T : in out Test); procedure Test_Max_Severity (T : in out Test); procedure Test_Get_Messages (T : in out Test); -- Test adding some exception in the faces context. procedure Test_Queue_Exception (T : in out Test); -- Test the flash instance. procedure Test_Flash_Context (T : in out Test); -- Test the mockup faces context. procedure Test_Mockup_Faces_Context (T : in out Test); end ASF.Contexts.Faces.Tests;
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with EL.Contexts.Default; with EL.Variables; with ASF.Tests; with ASF.Applications.Tests; with ASF.Helpers.Beans; package ASF.Contexts.Faces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); function Get_Form_Bean is new ASF.Helpers.Beans.Get_Bean (ASF.Applications.Tests.Form_Bean, ASF.Applications.Tests.Form_Bean_Access); type Test is new ASF.Tests.EL_Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. Form : ASF.Applications.Tests.Form_Bean_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out Test); -- Setup the faces context for the unit test. procedure Setup (T : in out Test; Context : in out Faces_Context); -- Test getting an attribute from the faces context. procedure Test_Get_Attribute (T : in out Test); -- Test getting a bean object from the faces context. procedure Test_Get_Bean (T : in out Test); -- Test getting a bean object from the faces context and doing a conversion. procedure Test_Get_Bean_Helper (T : in out Test); -- Test the faces message queue. procedure Test_Add_Message (T : in out Test); procedure Test_Max_Severity (T : in out Test); procedure Test_Get_Messages (T : in out Test); -- Test the application message factory for the creation of localized messages. procedure Test_Add_Localized_Message (T : in out Test); -- Test adding some exception in the faces context. procedure Test_Queue_Exception (T : in out Test); -- Test the flash instance. procedure Test_Flash_Context (T : in out Test); -- Test the mockup faces context. procedure Test_Mockup_Faces_Context (T : in out Test); end ASF.Contexts.Faces.Tests;
Declare the Test_Add_Localized_Message procedure for localization test
Declare the Test_Add_Localized_Message procedure for localization test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
007d9f908859bb1aed4ca6572586b14ade3928bf
src/babel-strategies-default.adb
src/babel-strategies-default.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; package body Babel.Strategies.Default is -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding function Peek_Directory (Strategy : in out Default_Strategy_Type) return String is Last : constant String := Strategy.Queue.Directories.Last_Element; begin Strategy.Queue.Directories.Delete_Last; return Last; end Peek_Directory; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 1.0); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; overriding procedure Add_File (Into : in out Default_Strategy_Type; Path : in String; Element : in Babel.Files.File) is begin Into.Queue.Add_File (Path, Element); end Add_File; overriding procedure Add_Directory (Into : in out Default_Strategy_Type; Path : in String; Name : in String) is begin Into.Queue.Add_Directory (Path, Name); end Add_Directory; end Babel.Strategies.Default;
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; package body Babel.Strategies.Default is -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return false; -- not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding procedure Peek_Directory (Strategy : in out Default_Strategy_Type; Directory : out Babel.Files.Directory_Type) is Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element; begin -- Strategy.Queue.Directories.Delete_Last; null; end Peek_Directory; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 1.0); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; -- Scan the directory overriding procedure Scan (Strategy : in out Default_Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is procedure Add_Queue (File : in Babel.Files.File_Type) is begin Strategy.Queue.Add_File (File); end Add_Queue; begin Strategy_Type (Strategy).Scan (Directory, Container); Container.Each_File (Add_Queue'Access); end Scan; -- overriding -- procedure Add_File (Into : in out Default_Strategy_Type; -- Path : in String; -- Element : in Babel.Files.File) is -- begin -- Into.Queue.Add_File (Path, Element); -- end Add_File; -- -- overriding -- procedure Add_Directory (Into : in out Default_Strategy_Type; -- Path : in String; -- Name : in String) is -- begin -- Into.Queue.Add_Directory (Path, Name); -- end Add_Directory; end Babel.Strategies.Default;
Implement the Scan procedure
Implement the Scan procedure
Ada
apache-2.0
stcarrez/babel
3c5667dfe519ee99f0ac3c26db75062779f8ce10
regtests/util-files-tests.adb
regtests/util-files-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Directories; with Util.Systems.Constants; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree", Test_Delete_Tree'Access); Caller.Add_Test (Suite, "Test Util.Files.Realpath", Test_Realpath'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink"; pragma Weak_External (Sys_Symlink); -- ------------------------------ -- Test the Delete_Tree operation. -- ------------------------------ procedure Test_Delete_Tree (T : in out Test) is use type System.Address; Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree"); begin if Ada.Directories.Exists (Path) then Delete_Tree (Path); end if; -- Create a directory tree with symlink links that point to a non-existing file. Ada.Directories.Create_Directory (Path); for I in 1 .. 10 loop declare P : constant String := Compose (Path, Util.Strings.Image (I)); S : String (1 .. P'Length + 3); R : Integer; begin Ada.Directories.Create_Directory (P); S (1 .. P'Length) := P; S (P'Length + 1) := '/'; S (P'Length + 2) := 'A'; S (S'Last) := ASCII.NUL; for J in 1 .. 5 loop Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J))); end loop; if Sys_Symlink'Address /= System.Null_Address then R := Sys_Symlink (S'Address, S'Address); Util.Tests.Assert_Equals (T, 0, R, "symlink creation failed"); end if; end; end loop; T.Assert (Ada.Directories.Exists (Path), "Directory must exist"); -- Ada.Directories.Delete_Tree (Path) fails to delete the tree. Delete_Tree (Path); T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted"); end Test_Delete_Tree; -- ------------------------------ -- Test the Realpath function. -- ------------------------------ procedure Test_Realpath (T : in out Test) is P : constant String := Util.Files.Realpath ("bin/util_harness"); begin Util.Tests.Assert_Matches (T, ".*/bin/util_harness", P); end Test_Realpath; end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Directories; with Util.Systems.Constants; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File_Missing'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Delete_Tree", Test_Delete_Tree'Access); Caller.Add_Test (Suite, "Test Util.Files.Realpath", Test_Realpath'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Unused_Result : Unbounded_String; begin Read_File (Path => "regtests/files-test--util.adb", Into => Unused_Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/sys/processes/os-none", Compose_Path ("src;regtests;src/sys/processes", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; function Sys_Symlink (Target : in System.Address; Link : in System.Address) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Constants.SYMBOL_PREFIX & "symlink"; pragma Weak_External (Sys_Symlink); -- ------------------------------ -- Test the Delete_Tree operation. -- ------------------------------ procedure Test_Delete_Tree (T : in out Test) is use type System.Address; Path : constant String := Util.Tests.Get_Test_Path ("test-delete-tree"); begin if Ada.Directories.Exists (Path) then Delete_Tree (Path); end if; -- Create a directory tree with symlink links that point to a non-existing file. Ada.Directories.Create_Directory (Path); for I in 1 .. 10 loop declare P : constant String := Compose (Path, Util.Strings.Image (I)); S : String (1 .. P'Length + 3); R : Integer; begin Ada.Directories.Create_Directory (P); S (1 .. P'Length) := P; S (P'Length + 1) := '/'; S (P'Length + 2) := 'A'; S (S'Last) := ASCII.NUL; for J in 1 .. 5 loop Ada.Directories.Create_Path (Compose (P, Util.Strings.Image (J))); end loop; if Sys_Symlink'Address /= System.Null_Address then R := Sys_Symlink (S'Address, S'Address); Util.Tests.Assert_Equals (T, 0, R, "symlink creation failed"); end if; end; end loop; T.Assert (Ada.Directories.Exists (Path), "Directory must exist"); -- Ada.Directories.Delete_Tree (Path) fails to delete the tree. Delete_Tree (Path); T.Assert (not Ada.Directories.Exists (Path), "Directory must have been deleted"); end Test_Delete_Tree; -- ------------------------------ -- Test the Realpath function. -- ------------------------------ procedure Test_Realpath (T : in out Test) is P : constant String := Util.Files.Realpath ("bin/util_harness"); begin Util.Tests.Assert_Matches (T, ".*/bin/util_harness", P); end Test_Realpath; end Util.Files.Tests;
Rename Unused_Result from Result
Rename Unused_Result from Result
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5a12aaec5bf3432fb2ccac881c08103c53341662
ARM/STM32/driver_demos/demo_LIS3DSH_pwm/src/demo_lis3dsh.adb
ARM/STM32/driver_demos/demo_LIS3DSH_pwm/src/demo_lis3dsh.adb
------------------------------------------------------------------------------ -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- This program demonstrates use of the LIS3DSH accelerometer and a timer to -- drive the brightness of the LEDs. -- Note that this demonstration program is specific to the STM32F4 Discovery -- boards because it references the specific accelerometer used on (later -- versions of) those boards and because it references the four user LEDs -- on those boards. (The LIS3DSH accelerometer is used on board versions -- designated by the number MB997C printed on the top of the board.) -- -- The idea is that the person holding the board will "pitch" it up and down -- and "roll" it left and right around the Z axis running through the center -- of the chip. As the board is moved, the brightness of the four LEDs -- surrounding the accelerometer will vary with the accelerations experienced -- by the board. In particular, as the angles increase the LEDs corresponding -- to those sides of the board will become brighter. The LEDs will thus become -- brightest as the board is held with any one side down, pointing toward the -- ground. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with Interfaces; use Interfaces; with Ada.Real_Time; use Ada.Real_Time; with STM32.Board; use STM32.Board; with LIS3DSH; use LIS3DSH; -- on the F4 Disco board with STM32.GPIO; use STM32.GPIO; with STM32.Timers; use STM32.Timers; with STM32.PWM; use STM32.PWM; use STM32; with Demo_PWM_Settings; use Demo_PWM_Settings; procedure Demo_LIS3DSH is Next_Release : Time := Clock; Period : constant Time_Span := Milliseconds (100); -- arbitrary function Brightness (Acceleration : Axis_Acceleration) return Percentage; -- Computes the output for the PWM. The approach is to compute the -- percentage of the given acceleration relative to a maximum acceleration -- of 1 G. procedure Drive_LEDs; -- Sets the pulse width for the two axes read from the accelerometer so -- that the brightness varies with the angle of the board. ---------------- -- Brightness -- ---------------- function Brightness (Acceleration : Axis_Acceleration) return Percentage is Result : Percentage; Bracketed_Value : Axis_Acceleration; Max_1g : constant Axis_Acceleration := 1000; -- The approximate reading from the accelerometer for 1g, in -- milligravities, used because this demo is for a person holding the -- board and rotating it, so at most approximately 1g will be seen on -- any axis. -- -- We bracket the value to the range -Max_1g .. Max_1g in order -- to filter out any movement beyond that of simply "pitching" and -- "rolling" around the Z axis running through the center of the chip. -- A person could move the board beyond the parameters intended for this -- demo simply by jerking the board laterally, for example. begin if Acceleration > 0 then Bracketed_Value := Axis_Acceleration'Min (Acceleration, Max_1g); else Bracketed_Value := Axis_Acceleration'Max (Acceleration, -Max_1g); end if; Result := Percentage ((Float (abs (Bracketed_Value)) / Float (Max_1g)) * 100.0); return Result; end Brightness; ---------------- -- Drive_LEDs -- ---------------- procedure Drive_LEDs is Axes : Axes_Accelerations; High_Threshold : constant Axis_Acceleration := 30; -- arbitrary Low_Threshold : constant Axis_Acceleration := -30; -- arbitrary Off : constant Percentage := 0; begin Accelerometer.Get_Accelerations (Axes); if Axes.X < Low_Threshold then Set_Duty_Cycle (PWM_Output, Channel_1, Brightness (Axes.X)); else Set_Duty_Cycle (PWM_Output, Channel_1, Off); end if; if Axes.X > High_Threshold then Set_Duty_Cycle (PWM_Output, Channel_3, Brightness (Axes.X)); else Set_Duty_Cycle (PWM_Output, Channel_3, Off); end if; if Axes.Y > High_Threshold then Set_Duty_Cycle (PWM_Output, Channel_2, Brightness (Axes.Y)); else Set_Duty_Cycle (PWM_Output, Channel_2, Off); end if; if Axes.Y < Low_Threshold then Set_Duty_Cycle (PWM_Output, Channel_4, Brightness (Axes.Y)); else Set_Duty_Cycle (PWM_Output, Channel_4, Off); end if; end Drive_LEDs; begin Initialize_Accelerometer; Accelerometer.Configure (Output_DataRate => Data_Rate_100Hz, Axes_Enable => XYZ_Enabled, SPI_Wire => Serial_Interface_4Wire, Self_Test => Self_Test_Normal, Full_Scale => Fullscale_2g, Filter_BW => Filter_800Hz); if Accelerometer.Device_Id /= I_Am_LIS3DSH then raise Program_Error with "invalid accelerometer"; end if; Initialise_PWM_Modulator (PWM_Output, Requested_Frequency => PWM_Frequency, PWM_Timer => PWM_Output_Timer'Access, PWM_AF => PWM_Output_AF); Attach_PWM_Channel (PWM_Output, Channel => Channel_1, Point => Channel_1_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_2, Point => Channel_2_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_3, Point => Channel_3_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_4, Point => Channel_4_Point); loop Drive_LEDs; Next_Release := Next_Release + Period; delay until Next_Release; end loop; end Demo_LIS3DSH;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This program demonstrates use of the LIS3DSH accelerometer and a timer to -- drive the brightness of the LEDs. -- Note that this demonstration program is specific to the STM32F4 Discovery -- boards because it references the specific accelerometer used on (later -- versions of) those boards and because it references the four user LEDs -- on those boards. (The LIS3DSH accelerometer is used on board versions -- designated by the number MB997C printed on the top of the board.) -- -- The idea is that the person holding the board will "pitch" it up and down -- and "roll" it left and right around the Z axis running through the center -- of the chip. As the board is moved, the brightness of the four LEDs -- surrounding the accelerometer will vary with the accelerations experienced -- by the board. In particular, as the angles increase the LEDs corresponding -- to those sides of the board will become brighter. The LEDs will thus become -- brightest as the board is held with any one side down, pointing toward the -- ground. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with Interfaces; use Interfaces; with Ada.Real_Time; use Ada.Real_Time; with STM32.Board; use STM32.Board; with LIS3DSH; use LIS3DSH; -- on the F4 Disco board with STM32.GPIO; use STM32.GPIO; with STM32.Timers; use STM32.Timers; with STM32.PWM; use STM32.PWM; use STM32; with Demo_PWM_Settings; use Demo_PWM_Settings; procedure Demo_LIS3DSH is Next_Release : Time := Clock; Period : constant Time_Span := Milliseconds (100); -- arbitrary function Brightness (Acceleration : Axis_Acceleration) return Percentage; -- Computes the output for the PWM. The approach is to compute the -- percentage of the given acceleration relative to a maximum acceleration -- of 1 G. procedure Drive_LEDs; -- Sets the pulse width for the two axes read from the accelerometer so -- that the brightness varies with the angle of the board. ---------------- -- Brightness -- ---------------- function Brightness (Acceleration : Axis_Acceleration) return Percentage is Result : Percentage; Bracketed_Value : Axis_Acceleration; Max_1g : constant Axis_Acceleration := 1000; -- The approximate reading from the accelerometer for 1g, in -- milligravities, used because this demo is for a person holding the -- board and rotating it, so at most approximately 1g will be seen on -- any axis. -- -- We bracket the value to the range -Max_1g .. Max_1g in order -- to filter out any movement beyond that of simply "pitching" and -- "rolling" around the Z axis running through the center of the chip. -- A person could move the board beyond the parameters intended for this -- demo simply by jerking the board laterally, for example. begin if Acceleration > 0 then Bracketed_Value := Axis_Acceleration'Min (Acceleration, Max_1g); else Bracketed_Value := Axis_Acceleration'Max (Acceleration, -Max_1g); end if; Result := Percentage ((Float (abs (Bracketed_Value)) / Float (Max_1g)) * 100.0); return Result; end Brightness; ---------------- -- Drive_LEDs -- ---------------- procedure Drive_LEDs is Axes : Axes_Accelerations; High_Threshold : constant Axis_Acceleration := 30; -- arbitrary Low_Threshold : constant Axis_Acceleration := -30; -- arbitrary Off : constant Percentage := 0; begin Accelerometer.Get_Accelerations (Axes); if Axes.X < Low_Threshold then Set_Duty_Cycle (PWM_Output, Channel_1, Brightness (Axes.X)); else Set_Duty_Cycle (PWM_Output, Channel_1, Off); end if; if Axes.X > High_Threshold then Set_Duty_Cycle (PWM_Output, Channel_3, Brightness (Axes.X)); else Set_Duty_Cycle (PWM_Output, Channel_3, Off); end if; if Axes.Y > High_Threshold then Set_Duty_Cycle (PWM_Output, Channel_2, Brightness (Axes.Y)); else Set_Duty_Cycle (PWM_Output, Channel_2, Off); end if; if Axes.Y < Low_Threshold then Set_Duty_Cycle (PWM_Output, Channel_4, Brightness (Axes.Y)); else Set_Duty_Cycle (PWM_Output, Channel_4, Off); end if; end Drive_LEDs; begin Initialize_Accelerometer; Accelerometer.Configure (Output_DataRate => Data_Rate_100Hz, Axes_Enable => XYZ_Enabled, SPI_Wire => Serial_Interface_4Wire, Self_Test => Self_Test_Normal, Full_Scale => Fullscale_2g, Filter_BW => Filter_800Hz); if Accelerometer.Device_Id /= I_Am_LIS3DSH then raise Program_Error with "invalid accelerometer"; end if; Initialise_PWM_Modulator (PWM_Output, Requested_Frequency => PWM_Frequency, PWM_Timer => PWM_Output_Timer'Access, PWM_AF => PWM_Output_AF); Attach_PWM_Channel (PWM_Output, Channel => Channel_1, Point => Channel_1_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_2, Point => Channel_2_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_3, Point => Channel_3_Point); Attach_PWM_Channel (PWM_Output, Channel => Channel_4, Point => Channel_4_Point); for C in Timer_Channel loop Enable_PWM_Channel (PWM_Output, C); end loop; loop Drive_LEDs; Next_Release := Next_Release + Period; delay until Next_Release; end loop; end Demo_LIS3DSH;
Call new procedure to enable the PWM channels
Call new procedure to enable the PWM channels
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library
414891d73d15aa39579a071328f7da6ae1eb1aad
src/asf-applications-main-configs.ads
src/asf-applications-main-configs.ads
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with EL.Contexts.Properties; with ASF.Contexts.Faces; with ASF.Applications.Main; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package ASF.Applications.Main.Configs is -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> procedure Read_Configuration (App : in out Application'Class; File : in String); -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. generic Reader : in out Util.Serialize.IO.XML.Parser; App : in ASF.Contexts.Faces.Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean := False; package Reader_Config is Prop_Context : aliased EL.Contexts.Properties.Property_Resolver; end Reader_Config; -- 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); end Parameter; -- ------------------------------ -- Application Specific Configuration -- ------------------------------ -- Read the application specific configuration by using the XML mapper. -- The application configuration looks like: -- -- <application> -- <message-bundle>name</message-bundle> -- <message-bundle var='name'>bundle-name</message-bundle> -- </application> -- type Application_Config is limited record Name : Util.Beans.Objects.Object; App : ASF.Contexts.Faces.Application_Access; end record; type Application_Config_Access is access all Application_Config; type Application_Fields is (TAG_MESSAGE_BUNDLE, TAG_MESSAGE_VAR, TAG_DEFAULT_LOCALE, TAG_SUPPORTED_LOCALE); -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object); private package Application_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Application_Config, Element_Type_Access => Application_Config_Access, Fields => Application_Fields, Set_Member => Set_Member); end ASF.Applications.Main.Configs;
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with EL.Contexts.Properties; with ASF.Contexts.Faces; with ASF.Applications.Main; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package ASF.Applications.Main.Configs is -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> procedure Read_Configuration (App : in out Application'Class; File : in String); -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. generic Mapper : in out Util.Serialize.Mappers.Processing; App : in ASF.Contexts.Faces.Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean := False; package Reader_Config is Prop_Context : aliased EL.Contexts.Properties.Property_Resolver; end Reader_Config; -- 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); end Parameter; -- ------------------------------ -- Application Specific Configuration -- ------------------------------ -- Read the application specific configuration by using the XML mapper. -- The application configuration looks like: -- -- <application> -- <message-bundle>name</message-bundle> -- <message-bundle var='name'>bundle-name</message-bundle> -- </application> -- type Application_Config is limited record Name : Util.Beans.Objects.Object; App : ASF.Contexts.Faces.Application_Access; end record; type Application_Config_Access is access all Application_Config; type Application_Fields is (TAG_MESSAGE_BUNDLE, TAG_MESSAGE_VAR, TAG_DEFAULT_LOCALE, TAG_SUPPORTED_LOCALE); -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object); private package Application_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Application_Config, Element_Type_Access => Application_Config_Access, Fields => Application_Fields, Set_Member => Set_Member); end ASF.Applications.Main.Configs;
Update the Reader_Config to use the new parser/mapper interface
Update the Reader_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
174bafb5c13248c2196b3724028e73e9cb556812
src/gen-artifacts-distribs-copies.adb
src/gen-artifacts-distribs-copies.adb
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- 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 Util.Log.Loggers; -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. package body Gen.Artifacts.Distribs.Copies is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Copies"); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is pragma Unreferenced (Node); Result : constant Copy_Rule_Access := new Copy_Rule; begin return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Copy_Rule) return String is pragma Unreferenced (Rule); begin return "copy"; end Get_Install_Name; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is pragma Unreferenced (Rule, Context); Source : constant String := Get_First_Path (Files); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Log.Info ("copy {0} to {1}", Source, Path); Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Source, Target_Name => Path, Form => "preserve=all_attributes, mode=overwrite"); end Install; end Gen.Artifacts.Distribs.Copies;
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- 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.Directories; with Util.Log.Loggers; -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. package body Gen.Artifacts.Distribs.Copies is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Copies"); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node; Copy_First_File : in Boolean) return Distrib_Rule_Access is pragma Unreferenced (Node); Result : constant Copy_Rule_Access := new Copy_Rule; begin Result.Copy_First_File := Copy_First_File; return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Copy_Rule) return String is pragma Unreferenced (Rule); begin return "copy"; end Get_Install_Name; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is pragma Unreferenced (Context); use type Ada.Containers.Count_Type; Source : constant String := Get_Source_Path (Files, Rule.Copy_First_File); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if Files.Length > 1 then Log.Info ("copy {0} to {1} (ignoring {2} files)", Source, Path, Natural'Image (Natural (Files.Length) - 1)); else Log.Info ("copy {0} to {1}", Source, Path); end if; Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Source, Target_Name => Path, Form => "preserve=all_attributes, mode=overwrite"); end Install; end Gen.Artifacts.Distribs.Copies;
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
1714efbd5dc3e9cf219b04c801ffcc161d98bfb5
src/orka/implementation/orka-jobs.adb
src/orka/implementation/orka-jobs.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Deallocation; package body Orka.Jobs is procedure Free (Pointer : in out Job_Ptr) is type Job_Access is access all Job'Class; procedure Free is new Ada.Unchecked_Deallocation (Object => Job'Class, Name => Job_Access); begin Free (Job_Access (Pointer)); end Free; overriding procedure Execute (Object : No_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is begin raise Program_Error with "Cannot execute Null_Job"; end Execute; overriding function Decrement_Dependencies (Object : in out Abstract_Job) return Boolean is use type Atomics.Unsigned_32; begin return Atomics.Decrement (Object.Dependencies) = 0; end Decrement_Dependencies; overriding function Has_Dependencies (Object : Abstract_Job) return Boolean is use type Atomics.Unsigned_32; begin return Object.Dependencies > 0; end Has_Dependencies; overriding procedure Set_Dependency (Object : access Abstract_Job; Dependency : Job_Ptr) is begin Atomics.Add (Object.Dependencies, 1); Abstract_Job (Dependency.all).Dependent := Job_Ptr (Object); end Set_Dependency; overriding procedure Set_Dependencies (Object : access Abstract_Job; Dependencies : Dependency_Array) is begin Atomics.Add (Object.Dependencies, Atomics.Unsigned_32 (Dependencies'Length)); for Dependency of Dependencies loop Abstract_Job (Dependency.all).Dependent := Job_Ptr (Object); end loop; end Set_Dependencies; procedure Chain (Jobs : Dependency_Array) is begin for Index in Jobs'First .. Jobs'Last - 1 loop Jobs (Index + 1).Set_Dependency (Jobs (Index)); end loop; end Chain; function Parallelize (Job : Parallel_Job_Ptr; Length, Slice : Positive) return Job_Ptr is begin return new Parallel_For_Job' (Abstract_Job with Length => Length, Slice => Slice, Job => Job); end Parallelize; overriding procedure Execute (Object : Parallel_For_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is Slice_Length : constant Positive := Positive'Min (Object.Length, Object.Slice); Slices : constant Positive := Object.Length / Slice_Length; Remaining : constant Natural := Object.Length rem Slice_Length; Array_Length : constant Positive := Slices + (if Remaining /= 0 then 1 else 0); Parallel_Jobs : constant Dependency_Array (1 .. Array_Length) := (others => new Parallel_Job'Class'(Object.Job.all)); From, To : Positive := 1; begin for Slice_Index in 1 .. Slices loop To := From + Slice_Length - 1; Parallel_Job'Class (Parallel_Jobs (Slice_Index).all).Set_Range (From, To); From := To + 1; end loop; if Remaining /= 0 then To := From + Slice_Length - 1 + Remaining; Parallel_Job'Class (Parallel_Jobs (Parallel_Jobs'Last).all).Set_Range (From, To); end if; pragma Assert (To = Object.Length); for Job of Parallel_Jobs loop Enqueue (Job); end loop; -- Object is still a (useless) dependency of Object.Dependent, -- but the worker that called this Execute procedure will decrement -- Object.Dependent.Dependencies after this procedure is done declare Original_Job : Job_Ptr := Job_Ptr (Object.Job); begin -- Copies of Object.Job have been made in Parallel_Jobs -- and these will be freed when they have been executed by -- workers. However, Object.Job itself will never be enqueued and -- executed by a worker (it just exists so we can copy it) so -- we need to manually free it. Free (Original_Job); end; end Execute; overriding procedure Execute (Object : Abstract_Parallel_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is begin Abstract_Parallel_Job'Class (Object).Execute (Object.From, Object.To); end Execute; overriding procedure Set_Range (Object : in out Abstract_Parallel_Job; From, To : Positive) is begin Object.From := From; Object.To := To; end Set_Range; end Orka.Jobs;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Deallocation; package body Orka.Jobs is procedure Free (Pointer : in out Job_Ptr) is type Job_Access is access all Job'Class; procedure Free is new Ada.Unchecked_Deallocation (Object => Job'Class, Name => Job_Access); begin Free (Job_Access (Pointer)); end Free; overriding procedure Execute (Object : No_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is begin raise Program_Error with "Cannot execute Null_Job"; end Execute; overriding function Decrement_Dependencies (Object : in out Abstract_Job) return Boolean is use type Atomics.Unsigned_32; begin return Atomics.Decrement (Object.Dependencies) = 0; end Decrement_Dependencies; overriding function Has_Dependencies (Object : Abstract_Job) return Boolean is use type Atomics.Unsigned_32; begin return Object.Dependencies > 0; end Has_Dependencies; overriding procedure Set_Dependency (Object : access Abstract_Job; Dependency : Job_Ptr) is begin Atomics.Add (Object.Dependencies, 1); Abstract_Job (Dependency.all).Dependent := Job_Ptr (Object); end Set_Dependency; overriding procedure Set_Dependencies (Object : access Abstract_Job; Dependencies : Dependency_Array) is begin Atomics.Add (Object.Dependencies, Atomics.Unsigned_32 (Dependencies'Length)); for Dependency of Dependencies loop Abstract_Job (Dependency.all).Dependent := Job_Ptr (Object); end loop; end Set_Dependencies; procedure Chain (Jobs : Dependency_Array) is begin for Index in Jobs'First .. Jobs'Last - 1 loop Jobs (Index + 1).Set_Dependency (Jobs (Index)); end loop; end Chain; function Parallelize (Job : Parallel_Job_Ptr; Length, Slice : Positive) return Job_Ptr is begin return new Parallel_For_Job' (Abstract_Job with Length => Length, Slice => Slice, Job => Job); end Parallelize; overriding procedure Execute (Object : Parallel_For_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is Slice_Length : constant Positive := Positive'Min (Object.Length, Object.Slice); Slices : constant Positive := Object.Length / Slice_Length; Remaining : constant Natural := Object.Length rem Slice_Length; Array_Length : constant Positive := Slices + (if Remaining /= 0 then 1 else 0); Parallel_Jobs : constant Dependency_Array (1 .. Array_Length) := (others => new Parallel_Job'Class'(Object.Job.all)); From, To : Positive := 1; begin for Slice_Index in 1 .. Slices loop To := From + Slice_Length - 1; Parallel_Job'Class (Parallel_Jobs (Slice_Index).all).Set_Range (From, To); From := To + 1; end loop; if Remaining /= 0 then To := From + Remaining - 1; Parallel_Job'Class (Parallel_Jobs (Parallel_Jobs'Last).all).Set_Range (From, To); end if; pragma Assert (To = Object.Length); for Job of Parallel_Jobs loop Enqueue (Job); end loop; -- Object is still a (useless) dependency of Object.Dependent, -- but the worker that called this Execute procedure will decrement -- Object.Dependent.Dependencies after this procedure is done declare Original_Job : Job_Ptr := Job_Ptr (Object.Job); begin -- Copies of Object.Job have been made in Parallel_Jobs -- and these will be freed when they have been executed by -- workers. However, Object.Job itself will never be enqueued and -- executed by a worker (it just exists so we can copy it) so -- we need to manually free it. Free (Original_Job); end; end Execute; overriding procedure Execute (Object : Abstract_Parallel_Job; Enqueue : not null access procedure (Element : Job_Ptr)) is begin Abstract_Parallel_Job'Class (Object).Execute (Object.From, Object.To); end Execute; overriding procedure Set_Range (Object : in out Abstract_Parallel_Job; From, To : Positive) is begin Object.From := From; Object.To := To; end Set_Range; end Orka.Jobs;
Fix Assert_Failure in Parallel_For_Job.Execute
orka: Fix Assert_Failure in Parallel_For_Job.Execute Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
a573d1eec1f2822916d3658910f6f7ce9b909e3d
src/sqlite/ado-connections-sqlite.adb
src/sqlite/ado-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 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 System; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with Util.Properties; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is Transactions : Integer; begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Util.Concurrent.Counters.Increment (Database.Transactions.all, Transactions); if Transactions = 0 then ADO.Statements.Sqlite.Execute (Database.Server, "BEGIN TRANSACTION"); end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Is_Zero : Boolean; begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; if Util.Concurrent.Counters.Value (Database.Transactions.all) > 0 then Util.Concurrent.Counters.Decrement (Database.Transactions.all, Is_Zero); if Is_Zero then ADO.Statements.Sqlite.Execute (Database.Server, "COMMIT TRANSACTION"); end if; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; if Util.Concurrent.Counters.Value (Database.Transactions.all) > 0 then Util.Concurrent.Counters.Decrement (Database.Transactions.all); ADO.Statements.Sqlite.Execute (Database.Server, "ROLLBACK TRANSACTION"); end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Close connection {0}", Database.Name); Database.Server := null; end Close; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; function Busy_Handler (Arg1 : System.Address; Count : Interfaces.C.int) return Interfaces.C.int with Convention => C; function Busy_Handler (Arg1 : System.Address; Count : Interfaces.C.int) return Interfaces.C.int is begin delay 0.001; return (if Count > 10_000 then 0 else 1); end Busy_Handler; protected body Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use Strings; URI : constant String := Config.Get_URI; Database : Database_Connection_Access; Pos : Database_List.Cursor := Database_List.First (List); DB : SQLite_Database; begin -- Look first in the database list. while Database_List.Has_Element (Pos) loop DB := Database_List.Element (Pos); if DB.URI = URI then Database := new Database_Connection; Database.URI := DB.URI; Database.Name := DB.Name; Database.Server := DB.Server; Database.Transactions := DB.Transactions; Result := Ref.Create (Database.all'Access); return; end if; Database_List.Next (Pos); end loop; -- Now we can open a new database connection. declare Name : constant String := Config.Get_Database; Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin if Config.Is_On (CREATE_NAME) then Flags := Flags + Sqlite3_H.SQLITE_OPEN_CREATE; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg; end; end if; Database := new Database_Connection; declare procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Name /= CREATE_NAME then if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := To_Unbounded_String (Config.Get_Database); Database.URI := To_Unbounded_String (URI); Database.Transactions := new Util.Concurrent.Counters.Counter; Result := Ref.Create (Database.all'Access); DB.Server := Handle; DB.Name := Database.Name; DB.URI := Database.URI; DB.Transactions := Database.Transactions; Database_List.Prepend (Container => List, New_Item => DB); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Iterate (Process => Configure'Access); Status := Sqlite3_H.sqlite3_busy_handler (Handle, Busy_Handler'Access, Database.all'Address); end; end; end Open; procedure Clear is DB : SQLite_Database; Result : int; begin while not Database_List.Is_Empty (List) loop DB := Database_List.First_Element (List); Database_List.Delete_First (List); if DB.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (DB.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg); end; end if; end if; end loop; end Clear; end Sqlite_Connections; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin D.Map.Open (Config, Result); end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D, Admin); Status : Integer; Database_Path : constant String := Config.Get_Database; Command : constant String := "sqlite3 --batch --init " & Schema_Path & " " & Database_Path; begin Log.Info ("Creating SQLite database {0}", Database_Path); Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Messages.Append ("Command not found: " & Command); Log.Error ("Command not found: {0}", Command); else Messages.Append ("Command " & Command & " failed with exit code " & Util.Strings.Image (Status)); Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the SQLite driver. -- ------------------------------ overriding procedure Finalize (D : in out Sqlite_Driver) is begin Log.Debug ("Deleting the sqlite driver"); D.Map.Clear; end Finalize; end ADO.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 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 System; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with Util.Properties; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is Transactions : Integer; begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Util.Concurrent.Counters.Increment (Database.Transactions.all, Transactions); if Transactions = 0 then ADO.Statements.Sqlite.Execute (Database.Server, "BEGIN TRANSACTION"); end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Is_Zero : Boolean; begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; if Util.Concurrent.Counters.Value (Database.Transactions.all) > 0 then Util.Concurrent.Counters.Decrement (Database.Transactions.all, Is_Zero); if Is_Zero then ADO.Statements.Sqlite.Execute (Database.Server, "COMMIT TRANSACTION"); end if; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; if Util.Concurrent.Counters.Value (Database.Transactions.all) > 0 then Util.Concurrent.Counters.Decrement (Database.Transactions.all); ADO.Statements.Sqlite.Execute (Database.Server, "ROLLBACK TRANSACTION"); end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Close connection {0}", Database.Name); Database.Server := null; end Close; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; function Busy_Handler (Arg1 : System.Address; Count : Interfaces.C.int) return Interfaces.C.int with Convention => C; function Busy_Handler (Arg1 : System.Address; Count : Interfaces.C.int) return Interfaces.C.int is begin delay 0.001; return (if Count > 10_000 then 0 else 1); end Busy_Handler; protected body Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use Strings; URI : constant String := Config.Get_URI; Database : Database_Connection_Access; Pos : Database_List.Cursor := Database_List.First (List); DB : SQLite_Database; begin -- Look first in the database list. while Database_List.Has_Element (Pos) loop DB := Database_List.Element (Pos); if DB.URI = URI then Database := new Database_Connection; Database.URI := DB.URI; Database.Name := DB.Name; Database.Server := DB.Server; Database.Transactions := DB.Transactions; Result := Ref.Create (Database.all'Access); return; end if; Database_List.Next (Pos); end loop; -- Now we can open a new database connection. declare Name : constant String := Config.Get_Database; Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin if Config.Is_On (CREATE_NAME) then Flags := Flags + Sqlite3_H.SQLITE_OPEN_CREATE; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg; end; end if; Database := new Database_Connection; declare procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Name /= CREATE_NAME then if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := To_Unbounded_String (Config.Get_Database); Database.URI := To_Unbounded_String (URI); Database.Transactions := new Util.Concurrent.Counters.Counter; Result := Ref.Create (Database.all'Access); DB.Server := Handle; DB.Name := Database.Name; DB.URI := Database.URI; DB.Transactions := Database.Transactions; Database_List.Prepend (Container => List, New_Item => DB); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Iterate (Process => Configure'Access); Status := Sqlite3_H.sqlite3_busy_handler (Handle, Busy_Handler'Access, Database.all'Address); if Status /= 0 then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot setup SQLite busy handler: {0}", Msg); end; end if; end; end; end Open; procedure Clear is DB : SQLite_Database; Result : int; begin while not Database_List.Is_Empty (List) loop DB := Database_List.First_Element (List); Database_List.Delete_First (List); if DB.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (DB.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg); end; end if; end if; end loop; end Clear; end Sqlite_Connections; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin D.Map.Open (Config, Result); end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D, Admin); Status : Integer; Database_Path : constant String := Config.Get_Database; Command : constant String := "sqlite3 --batch --init " & Schema_Path & " " & Database_Path; begin Log.Info ("Creating SQLite database {0}", Database_Path); Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Messages.Append ("Command not found: " & Command); Log.Error ("Command not found: {0}", Command); else Messages.Append ("Command " & Command & " failed with exit code " & Util.Strings.Image (Status)); Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the SQLite driver. -- ------------------------------ overriding procedure Finalize (D : in out Sqlite_Driver) is begin Log.Debug ("Deleting the sqlite driver"); D.Map.Clear; end Finalize; end ADO.Connections.Sqlite;
Check the error code returned by sqlite3_busy_handler
Check the error code returned by sqlite3_busy_handler
Ada
apache-2.0
stcarrez/ada-ado
aa4d7dd006e1f425c04c6ad23deb5a0efa01f4e6
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- 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.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True); -- Check the content. declare Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body); begin Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content"); end; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
Fix a memory leak in the unit test
Fix a memory leak in the unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
14134fd84b67c736cb2cc9e92229820a35e4bc79
testcases/prep_stmt/prep_stmt.adb
testcases/prep_stmt/prep_stmt.adb
with AdaBase; with Connect; with Ada.Text_IO; with CommonText; with AdaBase.Results.Sets; with AdaBase.Logger.Facility; procedure Prep_Stmt is package CON renames Connect; package TIO renames Ada.Text_IO; package CT renames CommonText; package AR renames AdaBase.Results; package ARS renames AdaBase.Results.Sets; package ALF renames AdaBase.Logger.Facility; begin CON.DR.command_standard_logger (device => ALF.screen, action => ALF.attach); declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare max_calories : aliased AR.byte2 := 200; min_calories : constant AR.byte2 := 5; row : ARS.DataRow_Access; begin CON.STMT := CON.DR.prepare_select (tables => "fruits", columns => "*", conditions => "color = ? and calories > :mincal and calories < ?"); CON.STMT.assign (1, "red"); CON.STMT.assign ("mincal", min_calories); CON.STMT.assign (3, max_calories'Unchecked_Access); if CON.STMT.execute then TIO.Put_Line ("execute succeeded"); for c in Natural range 1 .. CON.STMT.column_count loop TIO.Put_Line ("Column" & c'Img & " heading: " & CON.STMT.column_name (c)); end loop; TIO.Put_Line ("returned rows: " & CON.STMT.rows_returned'Img); loop exit when not CON.STMT.fetch_next (row); TIO.Put_Line (row.column (2).as_string & " (" & row.column ("color").as_string & ") " & row.column ("calories").as_string & " calories"); end loop; else TIO.Put_Line ("execute failed"); end if; end; declare sql : String := "INSERT INTO fruits (fruit, color, calories) " & "VALUES ('potato','tan', 77)"; begin CON.STMT := CON.DR.prepare (sql); if CON.STMT.execute then TIO.Put_Line ("Inserted row " & CON.STMT.last_insert_id'Img); end if; CON.DR.rollback; end; CON.DR.disconnect; end Prep_Stmt;
with AdaBase; with Connect; with Ada.Text_IO; with CommonText; with AdaBase.Results.Sets; with AdaBase.Logger.Facility; procedure Prep_Stmt is package CON renames Connect; package TIO renames Ada.Text_IO; package CT renames CommonText; package AR renames AdaBase.Results; package ARS renames AdaBase.Results.Sets; package ALF renames AdaBase.Logger.Facility; begin CON.DR.command_standard_logger (device => ALF.screen, action => ALF.attach); declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare max_calories : aliased AR.byte2 := 200; min_calories : constant AR.byte2 := 5; row : ARS.DataRow_Access; begin CON.STMT := CON.DR.prepare_select (tables => "fruits", columns => "*", conditions => "color = ? and calories > :mincal and calories < ?"); CON.STMT.assign (1, "red"); CON.STMT.assign ("mincal", min_calories); CON.STMT.assign (3, max_calories'Unchecked_Access); if CON.STMT.execute then TIO.Put_Line ("execute succeeded"); for c in Natural range 1 .. CON.STMT.column_count loop TIO.Put_Line ("Column" & c'Img & " heading: " & CON.STMT.column_name (c)); end loop; TIO.Put_Line ("returned rows: " & CON.STMT.rows_returned'Img); loop exit when not CON.STMT.fetch_next (row); TIO.Put_Line (row.column (2).as_string & " (" & row.column ("color").as_string & ") " & row.column ("calories").as_string & " calories"); end loop; else TIO.Put_Line ("execute failed"); end if; end; declare sql : String := "INSERT INTO fruits (fruit, color, calories) " & "VALUES ('potato','tan', 77)"; begin CON.STMT := CON.DR.prepare (sql); if CON.STMT.execute then TIO.Put_Line ("Inserted row " & CON.STMT.last_insert_id'Img); TIO.Put_Line ("Affected rows: " & CON.STMT.rows_affected'Img); end if; CON.DR.rollback; end; CON.DR.disconnect; end Prep_Stmt;
add stmt.affected_rows demonstration to last test case
add stmt.affected_rows demonstration to last test case
Ada
isc
jrmarino/AdaBase
b3db721649afe438c5be643fed9762ed718b7257
matp/src/memory/mat-memory-targets.ads
matp/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Events.Probes; 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; Used_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; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Find the region that matches the given name. function Find_Region (Memory : in Target_Memory; Name : in String) return 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 (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; Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- 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; Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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 Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Events.Probes; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is Not_Found : exception; -- 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; Used_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; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Find the region that matches the given name. function Find_Region (Memory : in Target_Memory; Name : in String) return 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 (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; Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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); -- Find the region that matches the given name. function Find_Region (Name : in String) return Region_Info; -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- 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; Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Targets.Event_Id_Type); -- 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 Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Declare the Find_Region protected procedure and the Not_Found exception
Declare the Find_Region protected procedure and the Not_Found exception
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f9a1d5bf5705d6b372f0a950b67e6e98dc2e3361
awa/plugins/awa-setup/src/awa-setup-applications.adb
awa/plugins/awa-setup/src/awa-setup-applications.adb
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Processes; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Context_Path : constant String := Request.Get_Context_Path; begin Response.Send_Redirect (Context_Path & "/setup/install.html"); end Do_Get; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); elsif Name = "database_driver" then return From.Driver; -- Util.Beans.Objects.To_Object (From.Database.Get_Driver); elsif Name = "database_root_user" then return From.Root_User; elsif Name = "database_root_password" then return From.Root_Passwd; elsif Name = "result" then return From.Result; end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "database_driver" then From.Driver := Value; elsif Name = "database_root_user" then From.Root_User := Value; elsif Name = "database_root_password" then From.Root_Passwd := Value; elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Get the database connection string to be used by the application. -- ------------------------------ function Get_Database_URL (From : in Application) return String is use Ada.Strings.Unbounded; Result : Ada.Strings.Unbounded.Unbounded_String; Driver : constant String := Util.Beans.Objects.To_String (From.Driver); begin if Driver = "" then Append (Result, "mysql"); else Append (Result, Driver); end if; Append (Result, "://"); if Driver /= "sqlite" then Append (Result, From.Database.Get_Server); if From.Database.Get_Port /= 0 then Append (Result, ":"); Append (Result, Util.Strings.Image (From.Database.Get_Port)); end if; end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if From.Database.Get_Property ("user") /= "" then Append (Result, "?user="); Append (Result, From.Database.Get_Property ("user")); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; if Driver = "sqlite" then Append (Result, "synchronous=OFF&encoding=UTF-8"); end if; return To_String (Result); end Get_Database_URL; -- ------------------------------ -- Get the command to configure the database. -- ------------------------------ function Get_Configure_Command (From : in Application) return String is Driver : constant String := Util.Beans.Objects.To_String (From.Driver); Database : constant String := From.Get_Database_URL; Command : constant String := "dynamo create-database db '" & Database & "'"; Root : constant String := Util.Beans.Objects.To_String (From.Root_User); Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd); begin if Root = "" then return Command; elsif Passwd = "" then return Command & " " & Root; else return Command & " " & Root & " " & Passwd; end if; end Get_Configure_Command; -- ------------------------------ -- Configure the database. -- ------------------------------ procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Command : constant String := From.Get_Configure_Command; begin Log.Info ("Configure database with {0}", Command); Pipe.Open (Command, Util.Processes.READ); Buffer.Initialize (null, Pipe'Unchecked_Access, 64*1024); Buffer.Read (Content); Pipe.Close; From.Result := Util.Beans.Objects.To_Object (Content); end Configure_Database; -- ------------------------------ -- Save the configuration. -- ------------------------------ procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); From.Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => New_File, New_Name => Path); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Enter in the application setup -- ------------------------------ procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Error_Page (ASF.Responses.SC_NOT_FOUND, "/setup/install.html"); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "redirect", Server => App.Redirect'Unchecked_Access); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "redirect"); App.Add_Mapping (Pattern => "/setup/*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : constant Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); while not App.Done loop delay 5.0; end loop; Server.Remove_Application (App'Unchecked_Access); end Setup; end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Processes; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Context_Path : constant String := Request.Get_Context_Path; begin Response.Send_Redirect (Context_Path & "/setup/install.html"); end Do_Get; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); elsif Name = "database_driver" then return From.Driver; -- Util.Beans.Objects.To_Object (From.Database.Get_Driver); elsif Name = "database_root_user" then return From.Root_User; elsif Name = "database_root_password" then return From.Root_Passwd; elsif Name = "result" then return From.Result; end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "database_driver" then From.Driver := Value; elsif Name = "database_root_user" then From.Root_User := Value; elsif Name = "database_root_password" then From.Root_Passwd := Value; elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Get the database connection string to be used by the application. -- ------------------------------ function Get_Database_URL (From : in Application) return String is use Ada.Strings.Unbounded; Result : Ada.Strings.Unbounded.Unbounded_String; Driver : constant String := Util.Beans.Objects.To_String (From.Driver); User : constant String := From.Database.Get_Property ("user"); begin if Driver = "" then Append (Result, "mysql"); else Append (Result, Driver); end if; Append (Result, "://"); if Driver /= "sqlite" then Append (Result, From.Database.Get_Server); if From.Database.Get_Port /= 0 then Append (Result, ":"); Append (Result, Util.Strings.Image (From.Database.Get_Port)); end if; end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if User /= "" then Append (Result, "?user="); Append (Result, User); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; if Driver = "sqlite" then if User /= "" then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, "synchronous=OFF&encoding=UTF-8"); end if; return To_String (Result); end Get_Database_URL; -- ------------------------------ -- Get the command to configure the database. -- ------------------------------ function Get_Configure_Command (From : in Application) return String is Driver : constant String := Util.Beans.Objects.To_String (From.Driver); Database : constant String := From.Get_Database_URL; Command : constant String := "dynamo create-database db '" & Database & "'"; Root : constant String := Util.Beans.Objects.To_String (From.Root_User); Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd); begin if Root = "" then return Command; elsif Passwd = "" then return Command & " " & Root; else return Command & " " & Root & " " & Passwd; end if; end Get_Configure_Command; -- ------------------------------ -- Configure the database. -- ------------------------------ procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Command : constant String := From.Get_Configure_Command; begin Log.Info ("Configure database with {0}", Command); Pipe.Open (Command, Util.Processes.READ); Buffer.Initialize (null, Pipe'Unchecked_Access, 64*1024); Buffer.Read (Content); Pipe.Close; From.Result := Util.Beans.Objects.To_Object (Content); end Configure_Database; -- ------------------------------ -- Save the configuration. -- ------------------------------ procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); From.Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => New_File, New_Name => Path); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Enter in the application setup -- ------------------------------ procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Error_Page (ASF.Responses.SC_NOT_FOUND, "/setup/install.html"); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "redirect", Server => App.Redirect'Unchecked_Access); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "redirect"); App.Add_Mapping (Pattern => "/setup/*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : constant Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); else App.Changed.Set ("callback_url", "http://mydomain.com/oauth"); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); while not App.Done loop delay 5.0; end loop; Server.Remove_Application (App'Unchecked_Access); end Setup; end AWA.Setup.Applications;
Update the database connection string for sqlite database
Update the database connection string for sqlite database
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ec3e91feea684adc9cc8e4530b76b3f9106d1c19
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Parts; with ASF.Parts.Upload_Method; with ASF.Events.Faces.Actions; with AWA.Storages.Services; package body AWA.Storages.Beans is package Upload_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean, Method => Upload, Name => "upload"); package Save_Part_Binding is new ASF.Parts.Upload_Method.Bind (Name => "save", Bean => Upload_Bean, Method => Save_Part); Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Upload_Binding.Proxy'Access, 2 => Save_Part_Binding.Proxy'Access); -- ------------------------------ -- 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 return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); 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 begin null; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Upload_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Upload_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : AWA.Storages.Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- Upload the file. procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Upload; -- ------------------------------ -- 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; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- 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 ASF.Parts; with ASF.Parts.Upload_Method; with ASF.Events.Faces.Actions; with AWA.Storages.Services; package body AWA.Storages.Beans is package Upload_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Upload_Bean, Method => Upload, Name => "upload"); package Save_Part_Binding is new ASF.Parts.Upload_Method.Bind (Name => "save", Bean => Upload_Bean, Method => Save_Part); Upload_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Upload_Binding.Proxy'Access, 2 => Save_Part_Binding.Proxy'Access); -- ------------------------------ -- 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 return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); 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 begin null; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Upload_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Upload_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : AWA.Storages.Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Bean.Set_Name (Part.Get_Name); Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- Upload the file. procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Upload; -- ------------------------------ -- 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; end AWA.Storages.Beans;
Set the name, file size and content type
Set the name, file size and content type
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
9170e4748af27db7ea6415b5fae18e74e27380aa
src/asf-contexts-facelets.adb
src/asf-contexts-facelets.adb
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : constant Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Facelet_Context'Class (Context).Get_Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Facelet_Context'Class (Context).Get_Application.Find_Validator (Name); end Get_Validator; end ASF.Contexts.Facelets;
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : constant Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; end ASF.Contexts.Facelets;
Remove Get_Converter and Get_Validator which are now abstract Remove Get_Application which is no longer necessary
Remove Get_Converter and Get_Validator which are now abstract Remove Get_Application which is no longer necessary
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
63bb84d3149620d0a42f1456014d184fd3a76b8b
src/base/files/util-files.adb
src/base/files/util-files.adb
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 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 Interfaces.C.Strings; with Ada.Directories; with Ada.IO_Exceptions; with Ada.Strings.Fixed; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Builders; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. -- ------------------------------ procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector) is procedure Append (Line : in String); procedure Append (Line : in String) is begin Into.Append (Line); end Append; begin Read_File (Path, Append'Access); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : in String; Paths : in String; Separator : in String := ";") return String is use Ada.Strings.Fixed; Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Index (Paths, Separator, Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare use Ada.Directories; Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Util.Strings.Builders.Builder (256); -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Util.Strings.Builders.Length (Result) > 0 then Util.Strings.Builders.Append (Result, Separator); end if; Util.Strings.Builders.Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return Util.Strings.Builders.To_Array (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or else Directory = "./" then if Name (Name'First) = '/' then return Compose (Directory, Name (Name'First + 1 .. Name'Last)); else return Name; end if; elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; -- ------------------------------ -- Rename the old name into a new name. -- ------------------------------ procedure Rename (Old_Name, New_Name : in String) is -- Rename a file (the Ada.Directories.Rename does not allow to use the -- Unix atomic file rename!) function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr; Newpath : in Interfaces.C.Strings.chars_ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); Old_Path : Interfaces.C.Strings.chars_ptr; New_Path : Interfaces.C.Strings.chars_ptr; Result : Integer; begin -- Do a system atomic rename of old file in the new file. -- Ada.Directories.Rename does not allow this. Old_Path := Interfaces.C.Strings.New_String (Old_Name); New_Path := Interfaces.C.Strings.New_String (New_Name); Result := Sys_Rename (Old_Path, New_Path); Interfaces.C.Strings.Free (Old_Path); Interfaces.C.Strings.Free (New_Path); if Result /= 0 then raise Ada.IO_Exceptions.Use_Error with "Cannot rename file"; end if; end Rename; end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 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 Interfaces.C.Strings; with Ada.Directories; with Ada.IO_Exceptions; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Text_IO; with Util.Strings.Builders; with Util.Strings.Tokenizers; package body Util.Files is -- ------------------------------ -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. -- ------------------------------ procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0) is use Ada.Streams; use Ada.Streams.Stream_IO; F : File_Type; Buffer : Stream_Element_Array (1 .. 10_000); Pos : Positive_Count := 1; Last : Stream_Element_Offset; Space : Natural; begin if Max_Size = 0 then Space := Natural'Last; else Space := Max_Size; end if; Open (Name => Path, File => F, Mode => In_File); loop Read (File => F, Item => Buffer, From => Pos, Last => Last); if Natural (Last) > Space then Last := Stream_Element_Offset (Space); end if; for I in 1 .. Last loop Append (Into, Character'Val (Buffer (I))); end loop; exit when Last < Buffer'Length; Pos := Pos + Positive_Count (Last); end loop; Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. -- ------------------------------ procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Open (File => File, Mode => Ada.Text_IO.In_File, Name => Path); while not Ada.Text_IO.End_Of_File (File) loop Process (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); end Read_File; -- ------------------------------ -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. -- ------------------------------ procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector) is procedure Append (Line : in String); procedure Append (Line : in String) is begin Into.Append (Line); end Append; begin Read_File (Path, Append'Access); end Read_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in String) is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; F : File_Type; Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First) .. Stream_Element_Offset (Content'Last)); Dir : constant String := Containing_Directory (Path); begin if not Exists (Dir) then Create_Path (Dir); end if; Create (File => F, Name => Path); for I in Content'Range loop Buffer (Stream_Element_Offset (I)) := Stream_Element (Character'Pos (Content (I))); end loop; Write (F, Buffer); Close (F); exception when others => if Is_Open (F) then Close (F); end if; raise; end Write_File; -- ------------------------------ -- Save the string into a file creating the file if necessary -- ------------------------------ procedure Write_File (Path : in String; Content : in Unbounded_String) is begin Write_File (Path, Ada.Strings.Unbounded.To_String (Content)); end Write_File; -- ------------------------------ -- Iterate over the search directories defined in <b>Paths</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is begin Util.Strings.Tokenizers.Iterate_Tokens (Content => Path, Pattern => ";", Process => Process, Going => Going); end Iterate_Path; -- ------------------------------ -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. -- ------------------------------ function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String is Sep_Pos : Natural; Pos : Positive := Paths'First; Last : constant Natural := Paths'Last; begin while Pos <= Last loop Sep_Pos := Util.Strings.Index (Paths, Separator, Pos); if Sep_Pos = 0 then Sep_Pos := Last; else Sep_Pos := Sep_Pos - 1; end if; declare use Ada.Directories; Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name); begin if Exists (Path) and then Kind (Path) = Ordinary_File then return Path; end if; exception when Name_Error => null; end; Pos := Sep_Pos + 2; end loop; return Name; end Find_File_Path; -- ------------------------------ -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. -- ------------------------------ procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward) is procedure Find_Files (Dir : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Find_Files (Dir : in String; Done : out Boolean) is use Ada.Directories; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Ent : Directory_Entry_Type; Search : Search_Type; begin Done := False; Start_Search (Search, Directory => Dir, Pattern => Pattern, Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); begin Process (Name, File_Path, Done); exit when Done; end; end loop; end Find_Files; begin Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going); end Iterate_Files_Path; -- ------------------------------ -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. -- ------------------------------ procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map) is procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Find the files matching the pattern in <b>Dir</b>. -- ------------------------------ procedure Add_File (Name : in String; File_Path : in String; Done : out Boolean) is begin if not Into.Contains (Name) then Into.Insert (Name, File_Path); end if; Done := False; end Add_File; begin Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access); end Find_Files_Path; -- ------------------------------ -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. -- ------------------------------ function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String is procedure Compose (Dir : in String; Done : out Boolean); Result : Util.Strings.Builders.Builder (256); -- ------------------------------ -- Build the new path by checking if <b>Name</b> exists in <b>Dir</b> -- and appending the new path in the <b>Result</b>. -- ------------------------------ procedure Compose (Dir : in String; Done : out Boolean) is use Ada.Directories; Path : constant String := Util.Files.Compose (Dir, Name); begin Done := False; if Exists (Path) and then Kind (Path) = Directory then if Util.Strings.Builders.Length (Result) > 0 then Util.Strings.Builders.Append (Result, Separator); end if; Util.Strings.Builders.Append (Result, Path); end if; exception when Name_Error => null; end Compose; begin Iterate_Path (Path => Paths, Process => Compose'Access); return Util.Strings.Builders.To_Array (Result); end Compose_Path; -- ------------------------------ -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Name'Length = 0 then return Directory; elsif Directory'Length = 0 then return Name; elsif Directory = "." or else Directory = "./" then if Name (Name'First) = '/' then return Compose (Directory, Name (Name'First + 1 .. Name'Last)); else return Name; end if; elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. -- ------------------------------ function Get_Relative_Path (From : in String; To : in String) return String is Result : Unbounded_String; Last : Natural := 0; begin for I in From'Range loop if I > To'Last or else From (I) /= To (I) then -- Nothing in common, return the absolute path <b>To</b>. if Last <= From'First + 1 then return To; end if; for J in Last .. From'Last - 1 loop if From (J) = '/' or From (J) = '\' then Append (Result, "../"); end if; end loop; if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then Append (Result, "../"); Append (Result, To (Last .. To'Last)); end if; return To_String (Result); elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then Last := I + 1; end if; end loop; if To'Last = From'Last or (To'Last = From'Last + 1 and (To (To'Last) = '/' or To (To'Last) = '\')) then return "."; elsif Last = 0 then return To; elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then return To (From'Last + 2 .. To'Last); else return To (Last .. To'Last); end if; end Get_Relative_Path; -- ------------------------------ -- Rename the old name into a new name. -- ------------------------------ procedure Rename (Old_Name, New_Name : in String) is -- Rename a file (the Ada.Directories.Rename does not allow to use the -- Unix atomic file rename!) function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr; Newpath : in Interfaces.C.Strings.chars_ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); Old_Path : Interfaces.C.Strings.chars_ptr; New_Path : Interfaces.C.Strings.chars_ptr; Result : Integer; begin -- Do a system atomic rename of old file in the new file. -- Ada.Directories.Rename does not allow this. Old_Path := Interfaces.C.Strings.New_String (Old_Name); New_Path := Interfaces.C.Strings.New_String (New_Name); Result := Sys_Rename (Old_Path, New_Path); Interfaces.C.Strings.Free (Old_Path); Interfaces.C.Strings.Free (New_Path); if Result /= 0 then raise Ada.IO_Exceptions.Use_Error with "Cannot rename file"; end if; end Rename; end Util.Files;
Update Find_File_Path to use a Character for the Separator
Update Find_File_Path to use a Character for the Separator
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
18cb5a42494647230222eac7228729dea3f6e9d8
src/cbap.adb
src/cbap.adb
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- The software is provided "as is" and the author disclaims all warranties -- -- with regard to this software including all implied warranties of -- -- merchantability and fitness. In no event shall the author be liable for -- -- any special, direct, indirect, or consequential damages or any damages -- -- whatsoever resulting from loss of use, data or profits, whether in an -- -- action of contract, negligence or other tortious action, arising out of -- -- or in connection with the use or performance of this software. -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; with Ada.Containers.Hashed_Sets; with Ada.Command_Line; with Ada.Strings.Fixed; with Ada.Strings.Hash; package body CBAP is --------------------------------------------------------------------------- function To_Lower (Item: in String) return String renames Ada.Characters.Handling.To_Lower; --------------------------------------------------------------------------- type Callback_Data is record Hash : Ada.Containers.Hash_Type; Callback: Callbacks; Arg_Type: Argument_Types := Value; Case_Sensitive: Boolean := True; end record; function Hash (This: in Callback_Data) return Ada.Containers.Hash_Type is begin return This.Hash; end Hash; overriding function "=" (Left, Right: in Callback_Data) return Boolean is use type Ada.Containers.Hash_Type; begin return Left.Hash = Right.Hash; end "="; procedure Null_Callback (Item: in String) is null; Empty_Callback_Data: constant Callback_Data := Callback_Data'(0, Null_Callback'Access, Value, True); package Callback_Sets is new Ada.Containers.Hashed_Sets (Callback_Data, Hash, "="); --------------------------------------------------------------------------- Callback_Set: Callback_Sets.Set := Callback_Sets.Empty_Set; --------------------------------------------------------------------------- procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ) is Var: Callback_Data := Callback_Data'(0, Callback, Argument_Type, Case_Sensitive); begin if Ada.Strings.Fixed.Index (Called_On, "=", Called_On'First) /= 0 then raise Incorrect_Called_On with Called_On; end if; if Case_Sensitive then Var.Hash := Ada.Strings.Hash (Called_On); else Var.Hash := Ada.Strings.Hash (To_Lower (Called_On)); end if; Callback_Set.Insert (Var); exception when Constraint_Error => raise Constraint_Error with "Following argument already has callback registered: " & Called_On; end Register; --------------------------------------------------------------------------- procedure Process_Arguments is --------------------------------------------------------------------------- package CLI renames Ada.Command_Line; --------------------------------------------------------------------------- procedure Add_Inputs (From: in Natural) is begin if not (From < CLI.Argument_Count) then return; end if; for K in From + 1 .. CLI.Argument_Count loop Input_Arguments.Append (CLI.Argument (K)); end loop; end Add_Inputs; --------------------------------------------------------------------------- function Extract_Name (Item: in String) return String is begin return Item (Item'First .. Ada.Strings.Fixed.Index (Item, "=", Item'First) - 1); end Extract_Name; --------------------------------------------------------------------------- function Extract_Value (Item: in String) return String is begin return Item (Ada.Strings.Fixed.Index (Item, "=", Item'First) + 1 .. Item'Last); end Extract_Value; --------------------------------------------------------------------------- procedure Check_Callback (Item: in String) is Dummy_Callback : Callback_Data := Empty_Callback_Data; Actual_Callback : Callback_Data := Empty_Callback_Data; begin -- Check for case insensitive value callback Dummy_Callback.Hash := Ada.Strings.Hash (To_Lower (Item)); if Callback_Set.Contains (Dummy_Callback) then Actual_Callback := Callback_Sets.Element (Callback_Set.Find (Dummy_Callback)); if not (Actual_Callback.Case_Sensitive) and Actual_Callback.Arg_Type = Value then Actual_Callback.Callback (Item); return; end if; end if; -- Check for case sensitive value callback Dummy_Callback.Hash := Ada.Strings.Hash (Item); if Callback_Set.Contains (Dummy_Callback) then Actual_Callback := Callback_Sets.Element (Callback_Set.Find (Dummy_Callback)); if Actual_Callback.Arg_Type = Value and Actual_Callback.Case_Sensitive then Actual_Callback.Callback (Item); return; end if; end if; -- Check for case insensitive variable callback Dummy_Callback.Hash := Ada.Strings.Hash (To_Lower (Extract_Name (Item))); if Callback_Set.Contains (Dummy_Callback) then Actual_Callback := Callback_Sets.Element (Callback_Set.Find (Dummy_Callback)); if not (Actual_Callback.Case_Sensitive) and Actual_Callback.Arg_Type = Variable then Actual_Callback.Callback (Extract_Value (Item)); return; end if; end if; -- Check for case sensitive variable callback Dummy_Callback.Hash := Ada.Strings.Hash (Extract_Name (Item)); if Callback_Set.Contains (Dummy_Callback) then Actual_Callback := Callback_Sets.Element (Callback_Set.Find (Dummy_Callback)); if Actual_Callback.Arg_Type = Variable and Actual_Callback.Case_Sensitive then Actual_Callback.Callback (Extract_Value (Item)); return; end if; end if; -- No callback associated with argument has been found. Unknown_Arguments.Append (Item); end Check_Callback; --------------------------------------------------------------------------- begin if CLI.Argument_Count = 0 then return; end if; for K in 1 .. CLI.Argument_Count loop declare Arg: constant String := CLI.Argument (K); begin if Arg = "--" then Add_Inputs (K); return; end if; -- Strip leading hyphens if Arg'Length > 2 and then Arg (Arg'First .. Arg'First + 1) = "--" then Check_Callback (Arg (Arg'First + 2 .. Arg'Last)); elsif Arg'Length > 1 and then Arg (1 .. 1) = "-" then Check_Callback (Arg (Arg'First + 1 .. Arg'Last)); else Check_Callback (Arg); end if; end; end loop; end Process_Arguments; --------------------------------------------------------------------------- end CBAP;
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- The software is provided "as is" and the author disclaims all warranties -- -- with regard to this software including all implied warranties of -- -- merchantability and fitness. In no event shall the author be liable for -- -- any special, direct, indirect, or consequential damages or any damages -- -- whatsoever resulting from loss of use, data or profits, whether in an -- -- action of contract, negligence or other tortious action, arising out of -- -- or in connection with the use or performance of this software. -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; with Ada.Containers.Hashed_Sets; with Ada.Command_Line; with Ada.Strings.Fixed; with Ada.Strings.Hash; package body CBAP is --------------------------------------------------------------------------- function To_Lower (Item: in String) return String renames Ada.Characters.Handling.To_Lower; --------------------------------------------------------------------------- type Callback_Data is record Hash : Ada.Containers.Hash_Type; Callback: Callbacks; Arg_Type: Argument_Types := Value; Case_Sensitive: Boolean := True; end record; function Hash (This: in Callback_Data) return Ada.Containers.Hash_Type is begin return This.Hash; end Hash; overriding function "=" (Left, Right: in Callback_Data) return Boolean is use type Ada.Containers.Hash_Type; begin return Left.Hash = Right.Hash; end "="; procedure Null_Callback (Item: in String) is null; Empty_Callback_Data: constant Callback_Data := Callback_Data'(0, Null_Callback'Access, Value, True); package Callback_Sets is new Ada.Containers.Hashed_Sets (Callback_Data, Hash, "="); --------------------------------------------------------------------------- Callback_Set: Callback_Sets.Set := Callback_Sets.Empty_Set; --------------------------------------------------------------------------- procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ) is Var: Callback_Data := Callback_Data'(0, Callback, Argument_Type, Case_Sensitive); begin if Ada.Strings.Fixed.Index (Called_On, "=", Called_On'First) /= 0 then raise Incorrect_Called_On with Called_On; end if; if Case_Sensitive then Var.Hash := Ada.Strings.Hash (Called_On); else Var.Hash := Ada.Strings.Hash (To_Lower (Called_On)); end if; Callback_Set.Insert (Var); exception when Constraint_Error => raise Constraint_Error with "Following argument already has callback registered: " & Called_On; end Register; --------------------------------------------------------------------------- procedure Process_Arguments is --------------------------------------------------------------------------- package CLI renames Ada.Command_Line; --------------------------------------------------------------------------- procedure Add_Inputs (From: in Natural) is begin if not (From < CLI.Argument_Count) then return; end if; for K in From + 1 .. CLI.Argument_Count loop Input_Arguments.Append (CLI.Argument (K)); end loop; end Add_Inputs; --------------------------------------------------------------------------- function Extract_Name (Item: in String) return String is begin return Item (Item'First .. Ada.Strings.Fixed.Index (Item, "=", Item'First) - 1); end Extract_Name; --------------------------------------------------------------------------- function Extract_Value (Item: in String) return String is Pos: constant Natural := Ada.Strings.Fixed.Index (Item, "=", Item'First); begin if Pos = Item'Last then return ""; -- in case: "variable=" else return Item (Pos + 1 .. Item'Last); end if; end Extract_Value; --------------------------------------------------------------------------- procedure Check_Callback (Item: in String) is Dummy_Callback : Callback_Data := Empty_Callback_Data; Actual_Callback : Callback_Data := Empty_Callback_Data; begin Case_Check: -- loop over case sensitiviness for Case_Sensitive in Boolean'Range loop Arg_Type_Check: -- loop over argument type for Arg_Type in Argument_Types'Range loop if Arg_Type = Value then if Case_Sensitive then Dummy_Callback.Hash := Ada.Strings.Hash (Item); else Dummy_Callback.Hash := Ada.Strings.Hash (To_Lower (Item)); end if; else -- For Variable we need to need to hash name ONLY if Case_Sensitive then Dummy_Callback.Hash := Ada.Strings.Hash (Extract_Name (Item)); else Dummy_Callback.Hash := Ada.Strings.Hash (Extract_Name (To_Lower (Item))); end if; end if; if Callback_Set.Contains (Dummy_Callback) then Actual_Callback := Callback_Sets.Element (Callback_Set.Find (Dummy_Callback)); if Actual_Callback.Case_Sensitive = Case_Sensitive and Actual_Callback.Arg_Type = Arg_Type then if Arg_Type = Value then Actual_Callback.Callback (Item); return; else -- Special circuitry for Variable type declare Pos: constant Natural := Ada.Strings.Fixed.Index (Item, "=", Item'First); begin if Pos = 0 then Unknown_Arguments.Append (Item); return; else Actual_Callback.Callback (Extract_Value (Item)); return; end if; end; end if; end if; end if; -- Callback_Set.Contains end loop Arg_Type_Check; end loop Case_Check; -- No callback associated with argument has been found. Unknown_Arguments.Append (Item); end Check_Callback; --------------------------------------------------------------------------- begin if CLI.Argument_Count = 0 then return; end if; for K in 1 .. CLI.Argument_Count loop declare Arg: constant String := CLI.Argument (K); begin if Arg = "--" then Add_Inputs (K); return; end if; -- Strip leading hyphens if Arg'Length > 2 and then Arg (Arg'First .. Arg'First + 1) = "--" then Check_Callback (Arg (Arg'First + 2 .. Arg'Last)); elsif Arg'Length > 1 and then Arg (1 .. 1) = "-" then Check_Callback (Arg (Arg'First + 1 .. Arg'Last)); else Check_Callback (Arg); end if; end; end loop; end Process_Arguments; --------------------------------------------------------------------------- end CBAP;
Refactor implementation of Process_Arguments.
Refactor implementation of Process_Arguments. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/cbap
6455475c49197724916785301c435b2d6deb465f
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Util.Http; with Security.Permissions; -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The process is the following: -- -- o <b>Initialize</b> is called to configure the OpenID realm and set the -- OpenID return callback CB. -- o <b>Discover</b> is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- o <b>Associate</b> is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- o <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- o The user should be redirected to the authentication URL. -- o The OpenID provider authenticate the user and redirects the user to the callback CB. -- o The association is decoded from the callback parameter. -- o <b>Verify</b> is called with the association to check the result and -- obtain the authentication results. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The process is the following: -- -- o <b>Initialize</b> is called to configure the OpenID realm and set the -- OpenID return callback CB. -- o <b>Discover</b> is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- o <b>Associate</b> is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- o <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- o The user should be redirected to the authentication URL. -- o The OpenID provider authenticate the user and redirects the user to the callback CB. -- o The association is decoded from the callback parameter. -- o <b>Verify</b> is called with the association to check the result and -- obtain the authentication results. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
Include in generated dynamo documentation
Include in generated dynamo documentation
Ada
apache-2.0
stcarrez/ada-security
fdf7d767693bebddd3d76b4191a0a2996d27c027
src/security-random.ads
src/security-random.ads
----------------------------------------------------------------------- -- security-random -- Random numbers for nonce, secret keys, token generation -- 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.Streams; with Ada.Finalization; with Ada.Strings.Unbounded; private with Ada.Numerics.Discrete_Random; private with Interfaces; package Security.Random is type Generator is limited new Ada.Finalization.Limited_Controlled with private; -- Initialize the random generator. overriding procedure Initialize (Gen : in out Generator); -- Fill the array with pseudo-random numbers. procedure Generate (Gen : in out Generator; Into : out Ada.Streams.Stream_Element_Array); -- Generate a random sequence of bits and convert the result -- into a string in base64url. function Generate (Gen : in out Generator'Class; Bits : in Positive) return String; -- Generate a random sequence of bits, convert the result -- into a string in base64url and append it to the buffer. procedure Generate (Gen : in out Generator'Class; Bits : in Positive; Into : in out Ada.Strings.Unbounded.Unbounded_String); private package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); -- Protected type to allow using the random generator by several tasks. protected type Raw_Generator is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); procedure Reset; private -- Random number generator used for ID generation. Rand : Id_Random.Generator; end Raw_Generator; type Generator is new Ada.Finalization.Limited_Controlled with record Rand : Raw_Generator; end record; end Security.Random;
----------------------------------------------------------------------- -- security-random -- Random numbers for nonce, secret keys, token generation -- 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.Streams; with Ada.Finalization; with Ada.Strings.Unbounded; private with Ada.Numerics.Discrete_Random; private with Interfaces; package Security.Random is type Generator is limited new Ada.Finalization.Limited_Controlled with private; -- Initialize the random generator. overriding procedure Initialize (Gen : in out Generator); -- Fill the array with pseudo-random numbers. procedure Generate (Gen : in out Generator; Into : out Ada.Streams.Stream_Element_Array); -- Generate a random sequence of bits and convert the result -- into a string in base64url. function Generate (Gen : in out Generator'Class; Bits : in Positive) return String; -- Generate a random sequence of bits, convert the result -- into a string in base64url and append it to the buffer. procedure Generate (Gen : in out Generator'Class; Bits : in Positive; Into : in out Ada.Strings.Unbounded.Unbounded_String); private package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); -- Protected type to allow using the random generator by several tasks. protected type Raw_Generator is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); procedure Reset; private -- Random number generator used for ID generation. Rand : Id_Random.Generator; end Raw_Generator; type Generator is limited new Ada.Finalization.Limited_Controlled with record Rand : Raw_Generator; end record; end Security.Random;
Fix compilation with gnat-2016
Fix compilation with gnat-2016
Ada
apache-2.0
stcarrez/ada-security
12ffa3f4191edb7832e2fefcb828ec2a9e2dd213
src/sys/streams/util-streams.ads
src/sys/streams/util-streams.ads
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 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.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. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_sys"; -- -- @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-base16.ads -- @include util-streams-base64.ads -- @include util-streams-aes.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, 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.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. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_sys"; -- -- @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-base16.ads -- @include util-streams-base64.ads -- @include util-streams-aes.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); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream'Class; Item : in Character); procedure Write (Stream : in out Output_Stream'Class; Item : in String); -- Write a wide character on the stream using a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_Character); procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_String); -- 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 Write and Write_Wide procedures to help in writing character and strings
Add Write and Write_Wide procedures to help in writing character and strings
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e23418ab074e4daff231f8fd3c7070a3c31b5a41
src/atlas-applications.ads
src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 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 Util.Beans.Objects; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with Servlet.Core.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with ASF.Applications; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased Servlet.Core.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications -- Copyright (C) 2012, 2013, 2014, 2015, 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with Servlet.Core.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with ASF.Applications; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased Servlet.Core.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
Remove the Initialize procedure
Remove the Initialize procedure
Ada
apache-2.0
stcarrez/atlas
f6906580e6143a1f95220198f5e8b46bc5e4fd8f
src/util-dates-iso8601.adb
src/util-dates-iso8601.adb
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 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. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; use Ada.Calendar.Formatting; Result : Date_Record; Pos : Natural; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Hour := 0; Result.Minute := 0; Result.Second := 0; Result.Sub_Second := 0.0; Result.Time_Zone := 0; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); -- ISO8601 date: YYYY-MM-DDTHH if Date'Length > 12 then if Date (Date'First + 10) /= 'T' then raise Constraint_Error with "invalid date"; end if; Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12)); Pos := Date'First + 13; end if; if Date'Length > 15 then if Date (Date'First + 13) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15)); Pos := Date'First + 16; end if; if Date'Length > 18 then if Date (Date'First + 16) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18)); Pos := Date'First + 19; end if; -- ISO8601 timezone: +hh:mm or -hh:mm -- if Date'Length > Pos + 4 then -- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then -- raise Constraint_Error with "invalid date"; -- end if; -- end if; else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => Result.Hour, Minute => Result.Minute, Second => Result.Second, Sub_Second => Result.Sub_Second, Time_Zone => Result.Time_Zone); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String is D : Date_Record; begin Split (D, Date); return Image (D, Precision); end Image; function Image (Date : in Date_Record; Precision : in Precision_Type) return String is use type Ada.Calendar.Time_Zones.Time_Offset; To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00"; N, Tz : Natural; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); if Precision = YEAR then return Result (1 .. 4); end if; Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); if Precision = MONTH then return Result (1 .. 7); end if; Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); if Precision = DAY then return Result (1 .. 10); end if; Result (12) := To_Char (Date.Hour / 10); Result (13) := To_Char (Date.Hour mod 10); if Precision = HOUR then return Result (1 .. 13); end if; Result (15) := To_Char (Date.Minute / 10); Result (16) := To_Char (Date.Minute mod 10); if Precision = MINUTE then return Result (1 .. 16); end if; Result (18) := To_Char (Date.Second / 10); Result (19) := To_Char (Date.Second mod 10); if Precision = SECOND then return Result (1 .. 19); end if; N := Natural (Date.Sub_Second * 1000.0); Result (21) := To_Char (N / 100); Result (22) := To_Char ((N mod 100) / 10); Result (23) := To_Char (N mod 10); if Date.Time_Zone < 0 then Tz := Natural (-Date.Time_Zone); else Result (24) := '+'; Tz := Natural (Date.Time_Zone); end if; Result (25) := To_Char (Tz / 600); Result (26) := To_Char ((Tz / 60) mod 10); Tz := Tz mod 60; Result (28) := To_Char (Tz / 10); Result (29) := To_Char (Tz mod 10); return Result; end Image; end Util.Dates.ISO8601;
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; use Ada.Calendar.Formatting; Result : Date_Record; Pos : Natural; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Hour := 0; Result.Minute := 0; Result.Second := 0; Result.Sub_Second := 0.0; Result.Time_Zone := 0; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); -- ISO8601 date: YYYY-MM-DDTHH if Date'Length > 12 then if Date (Date'First + 10) /= 'T' then raise Constraint_Error with "invalid date"; end if; Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12)); Pos := Date'First + 13; end if; if Date'Length > 15 then if Date (Date'First + 13) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15)); Pos := Date'First + 16; end if; if Date'Length > 18 then if Date (Date'First + 16) /= ':' then raise Constraint_Error with "invalid date"; end if; Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18)); Pos := Date'First + 19; end if; -- ISO8601 timezone: +hh:mm or -hh:mm -- if Date'Length > Pos + 4 then -- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then -- raise Constraint_Error with "invalid date"; -- end if; -- end if; else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => Result.Hour, Minute => Result.Minute, Second => Result.Second, Sub_Second => Result.Sub_Second, Time_Zone => Result.Time_Zone); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; function Image (Date : in Ada.Calendar.Time; Precision : in Precision_Type) return String is D : Date_Record; begin Split (D, Date); return Image (D, Precision); end Image; function Image (Date : in Date_Record; Precision : in Precision_Type) return String is use type Ada.Calendar.Time_Zones.Time_Offset; To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00"; N, Tz : Natural; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); if Precision = YEAR then return Result (1 .. 4); end if; Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); if Precision = MONTH then return Result (1 .. 7); end if; Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); if Precision = DAY then return Result (1 .. 10); end if; Result (12) := To_Char (Date.Hour / 10); Result (13) := To_Char (Date.Hour mod 10); if Precision = HOUR then return Result (1 .. 13); end if; Result (15) := To_Char (Date.Minute / 10); Result (16) := To_Char (Date.Minute mod 10); if Precision = MINUTE then return Result (1 .. 16); end if; Result (18) := To_Char (Date.Second / 10); Result (19) := To_Char (Date.Second mod 10); if Precision = SECOND then return Result (1 .. 19); end if; N := Natural (Date.Sub_Second * 1000.0); Result (21) := To_Char (N / 100); Result (22) := To_Char ((N mod 100) / 10); Result (23) := To_Char (N mod 10); if Date.Time_Zone < 0 then Tz := Natural (-Date.Time_Zone); else Result (24) := '+'; Tz := Natural (Date.Time_Zone); end if; Result (25) := To_Char (Tz / 600); Result (26) := To_Char ((Tz / 60) mod 10); Tz := Tz mod 60; Result (28) := To_Char (Tz / 10); Result (29) := To_Char (Tz mod 10); return Result; end Image; end Util.Dates.ISO8601;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3e12147a647d6e8ab637440e1c828624b09bba98
awa/src/awa-wikis-writers-text.adb
awa/src/awa-wikis-writers-text.adb
----------------------------------------------------------------------- -- awa-wikis-writers-text -- Wiki HTML writer -- 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.Wikis.Writers.Text is use AWA.Wikis.Documents; -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Writer (Document : in out Text_Writer; Writer : in ASF.Contexts.Writer.Response_Writer_Access) is begin Document.Writer := Writer; end Set_Writer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Text_Writer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is pragma Unreferenced (Level); begin Document.Close_Paragraph; if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Writer.Write (Header); Document.Add_Line_Break; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Text_Writer) is begin Document.Writer.Write (ASCII.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Text_Writer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; Document.Add_Line_Break; end Add_Paragraph; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Text_Writer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; end Add_List_Item; procedure Close_Paragraph (Document : in out Text_Writer) 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_Writer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Text_Writer) is begin Document.Close_Paragraph; end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Text_Writer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Language); begin Document.Open_Paragraph; if Length (Title) > 0 then Document.Writer.Write (Title); end if; Document.Writer.Write (Link); Document.Writer.Write (Name); Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Text_Writer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; if Length (Alt) > 0 then Document.Writer.Write (Alt); end if; if Length (Description) > 0 then Document.Writer.Write (Description); end if; Document.Writer.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Text_Writer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Link, Language); begin Document.Open_Paragraph; Document.Writer.Write (Quote); Document.Empty_Line := False; end Add_Quote; -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Text_Writer; Text : in Unbounded_Wide_Wide_String; Format : in AWA.Wikis.Documents.Format_Map) is pragma Unreferenced (Format); begin Document.Writer.Write (Text); Document.Empty_Line := False; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Text_Writer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Format); begin Document.Close_Paragraph; Document.Writer.Write (Text); Document.Empty_Line := False; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Writer) is begin Document.Close_Paragraph; end Finish; end AWA.Wikis.Writers.Text;
----------------------------------------------------------------------- -- awa-wikis-writers-text -- Wiki HTML writer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Wikis.Writers.Text is use AWA.Wikis.Documents; -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Writer (Document : in out Text_Writer; Writer : in ASF.Contexts.Writer.Response_Writer_Access) is begin Document.Writer := Writer; end Set_Writer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Text_Writer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is pragma Unreferenced (Level); begin Document.Close_Paragraph; if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Writer.Write (Header); Document.Add_Line_Break; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Text_Writer) is begin Document.Writer.Write (ASCII.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Text_Writer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; Document.Add_Line_Break; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Text_Writer; Level : in Natural) is begin Document.Close_Paragraph; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Text_Writer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; end Add_List_Item; procedure Close_Paragraph (Document : in out Text_Writer) 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_Writer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Text_Writer) is begin Document.Close_Paragraph; end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Text_Writer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Language); begin Document.Open_Paragraph; if Length (Title) > 0 then Document.Writer.Write (Title); end if; Document.Writer.Write (Link); Document.Writer.Write (Name); Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Text_Writer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; if Length (Alt) > 0 then Document.Writer.Write (Alt); end if; if Length (Description) > 0 then Document.Writer.Write (Description); end if; Document.Writer.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Text_Writer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Link, Language); begin Document.Open_Paragraph; Document.Writer.Write (Quote); Document.Empty_Line := False; end Add_Quote; -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Text_Writer; Text : in Unbounded_Wide_Wide_String; Format : in AWA.Wikis.Documents.Format_Map) is pragma Unreferenced (Format); begin Document.Writer.Write (Text); Document.Empty_Line := False; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Text_Writer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Format); begin Document.Close_Paragraph; Document.Writer.Write (Text); Document.Empty_Line := False; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Writer) is begin Document.Close_Paragraph; end Finish; end AWA.Wikis.Writers.Text;
Implement the Add_Blockquote procedure
Implement the Add_Blockquote procedure
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
ff6e221b8f6718b4f7ac1aad4b9772e0e37ad6ba
asfunit/asf-tests.ads
asfunit/asf-tests.ads
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Servlet.Tests; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status) renames Servlet.Tests.Finish; -- Get the server function Get_Server return access ASF.Server.Container renames Servlet.Tests.Get_Server; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Get; -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Post; -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) renames Servlet.Tests.Do_Req; -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Contains; -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Matches; -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Redirect; -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Header; type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
Package ASF.Tests moved to Servlet.Tests
Package ASF.Tests moved to Servlet.Tests
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
bb5d30d32afcfa2a341a9137c40d0cafb52abeea
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; -- Get the number of nodes in the list. function Length (List : in Node_List_Ref) return Natural; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
Declare the Length procedure
Declare the Length procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
61770bb3c987802d6a0d345c0976e5182b6805e2
src/orka/implementation/orka-rendering-effects-filters.adb
src/orka/implementation/orka-rendering-effects-filters.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with GL.Pixels; with GL.Toggles; with Orka.Rendering.Drawing; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Textures; package body Orka.Rendering.Effects.Filters is package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double); use type GL.Types.Double; function Gaussian_Kernel (Radius : GL.Types.Size) return GL.Types.Single_Array is Sigma : constant GL.Types.Double := ((GL.Types.Double (Radius) - 1.0) * 0.5 - 1.0) * 0.3 + 0.8; Denominator : constant GL.Types.Double := EF.Sqrt (2.0 * Ada.Numerics.Pi * Sigma ** 2); Kernel : GL.Types.Double_Array (0 .. Radius); Sum : GL.Types.Double := 0.0; begin for Index in Kernel'Range loop Kernel (Index) := EF.Exp (-GL.Types.Double (Index**2) / (2.0 * Sigma ** 2)) / Denominator; Sum := Sum + Kernel (Index) * (if Index > 0 then 2.0 else 1.0); -- Kernel array only stores the positive side of the curve, but -- we need to compute the area of the whole curve for normalization end loop; -- Normalize the weights to prevent the image from becoming darker for Index in Kernel'Range loop Kernel (Index) := Kernel (Index) / Sum; end loop; declare -- Use bilinear texture filtering hardware [1]. -- -- Weight (t1, t2) = Weight (t1) + Weight (t2) -- -- offset (t1) * weight (t1) + offset (t2) * weight (t2) -- Offset (t1, t2) = ----------------------------------------------------- -- weight (t1, t2) -- -- [1] http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ Weights : GL.Types.Single_Array (0 .. Radius / 2); Offsets : GL.Types.Single_Array (0 .. Radius / 2); use type GL.Types.Single_Array; use GL.Types; begin Weights (Weights'First) := Single (Kernel (Weights'First)); Offsets (Offsets'First) := 0.0; -- Weights for Index in Weights'First + 1 .. Weights'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; begin Weights (Index) := Single (Kernel (T1) + Kernel (T2)); end; end loop; -- Offsets for Index in Offsets'First + 1 .. Offsets'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; W12 : constant Single := Weights (Index); begin if W12 > 0.0 then Offsets (Index) := Single ((Double (T1) * Kernel (T1) + Double (T2) * Kernel (T2)) / Double (W12)); else Offsets (Index) := 0.0; end if; end; end loop; return Offsets & Weights; end; end Gaussian_Kernel; function Create_Filter (Location : Resources.Locations.Location_Ptr; Subject : GL.Objects.Textures.Texture; Kernel : GL.Types.Single_Array) return Separable_Filter is use all type LE.Texture_Kind; pragma Assert (Subject.Kind = LE.Texture_Rectangle); use Rendering.Buffers; use Rendering.Framebuffers; use Rendering.Programs; Width : constant GL.Types.Size := Subject.Width (0); Height : constant GL.Types.Size := Subject.Height (0); begin return Result : Separable_Filter := (Buffer_Weights => Create_Buffer ((others => False), Kernel), Program_Blur => Create_Program (Modules.Module_Array' (Modules.Create_Module (Location, VS => "oversized-triangle.vert"), Modules.Create_Module (Location, FS => "effects/blur.frag"))), Framebuffer_H => Framebuffer_Ptr'(new Framebuffer'(Create_Framebuffer (Width, Height))), Framebuffer_V => Framebuffer_Ptr'(new Framebuffer'(Create_Framebuffer (Width, Height))), Texture_H => Subject, others => <>) do Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal"); Result.Texture_V.Allocate_Storage (Subject); Result.Framebuffer_H.Attach (Result.Texture_H); Result.Framebuffer_V.Attach (Result.Texture_V); end return; end Create_Filter; procedure Render (Object : in out Separable_Filter; Passes : Positive := 1) is use all type Orka.Rendering.Buffers.Indexed_Buffer_Target; begin GL.Toggles.Disable (GL.Toggles.Depth_Test); Object.Program_Blur.Use_Program; Object.Buffer_Weights.Bind (Shader_Storage, 0); for Pass in 1 .. Passes loop -- Horizontal pass: Texture_H => Texture_V Object.Uniform_Horizontal.Set_Boolean (True); Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_V.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); -- Vertical pass: Texture_V => Texture_H Object.Uniform_Horizontal.Set_Boolean (False); Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_H.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); end loop; GL.Toggles.Enable (GL.Toggles.Depth_Test); end Render; end Orka.Rendering.Effects.Filters;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with GL.Toggles; with Orka.Rendering.Drawing; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Textures; package body Orka.Rendering.Effects.Filters is package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double); use type GL.Types.Double; function Gaussian_Kernel (Radius : GL.Types.Size) return GL.Types.Single_Array is Sigma : constant GL.Types.Double := ((GL.Types.Double (Radius) - 1.0) * 0.5 - 1.0) * 0.3 + 0.8; Denominator : constant GL.Types.Double := EF.Sqrt (2.0 * Ada.Numerics.Pi * Sigma ** 2); Kernel : GL.Types.Double_Array (0 .. Radius); Sum : GL.Types.Double := 0.0; begin for Index in Kernel'Range loop Kernel (Index) := EF.Exp (-GL.Types.Double (Index**2) / (2.0 * Sigma ** 2)) / Denominator; Sum := Sum + Kernel (Index) * (if Index > 0 then 2.0 else 1.0); -- Kernel array only stores the positive side of the curve, but -- we need to compute the area of the whole curve for normalization end loop; -- Normalize the weights to prevent the image from becoming darker for Index in Kernel'Range loop Kernel (Index) := Kernel (Index) / Sum; end loop; declare -- Use bilinear texture filtering hardware [1]. -- -- Weight (t1, t2) = Weight (t1) + Weight (t2) -- -- offset (t1) * weight (t1) + offset (t2) * weight (t2) -- Offset (t1, t2) = ----------------------------------------------------- -- weight (t1, t2) -- -- [1] http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ Weights : GL.Types.Single_Array (0 .. Radius / 2); Offsets : GL.Types.Single_Array (0 .. Radius / 2); use type GL.Types.Single_Array; use GL.Types; begin Weights (Weights'First) := Single (Kernel (Weights'First)); Offsets (Offsets'First) := 0.0; -- Weights for Index in Weights'First + 1 .. Weights'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; begin Weights (Index) := Single (Kernel (T1) + Kernel (T2)); end; end loop; -- Offsets for Index in Offsets'First + 1 .. Offsets'Last loop declare T1 : constant Size := Index * 2 - 1; T2 : constant Size := Index * 2; W12 : constant Single := Weights (Index); begin if W12 > 0.0 then Offsets (Index) := Single ((Double (T1) * Kernel (T1) + Double (T2) * Kernel (T2)) / Double (W12)); else Offsets (Index) := 0.0; end if; end; end loop; return Offsets & Weights; end; end Gaussian_Kernel; function Create_Filter (Location : Resources.Locations.Location_Ptr; Subject : GL.Objects.Textures.Texture; Kernel : GL.Types.Single_Array) return Separable_Filter is use all type LE.Texture_Kind; pragma Assert (Subject.Kind = LE.Texture_Rectangle); use Rendering.Buffers; use Rendering.Framebuffers; use Rendering.Programs; Width : constant GL.Types.Size := Subject.Width (0); Height : constant GL.Types.Size := Subject.Height (0); begin return Result : Separable_Filter := (Buffer_Weights => Create_Buffer ((others => False), Kernel), Program_Blur => Create_Program (Modules.Module_Array' (Modules.Create_Module (Location, VS => "oversized-triangle.vert"), Modules.Create_Module (Location, FS => "effects/blur.frag"))), Framebuffer_H => Framebuffer_Ptr'(new Framebuffer'(Create_Framebuffer (Width, Height))), Framebuffer_V => Framebuffer_Ptr'(new Framebuffer'(Create_Framebuffer (Width, Height))), Texture_H => Subject, others => <>) do Result.Uniform_Horizontal := Result.Program_Blur.Uniform ("horizontal"); Result.Texture_V.Allocate_Storage (Subject); Result.Framebuffer_H.Attach (Result.Texture_H); Result.Framebuffer_V.Attach (Result.Texture_V); end return; end Create_Filter; procedure Render (Object : in out Separable_Filter; Passes : Positive := 1) is use all type Orka.Rendering.Buffers.Indexed_Buffer_Target; begin GL.Toggles.Disable (GL.Toggles.Depth_Test); Object.Program_Blur.Use_Program; Object.Buffer_Weights.Bind (Shader_Storage, 0); for Pass in 1 .. Passes loop -- Horizontal pass: Texture_H => Texture_V Object.Uniform_Horizontal.Set_Boolean (True); Orka.Rendering.Textures.Bind (Object.Texture_H, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_V.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); -- Vertical pass: Texture_V => Texture_H Object.Uniform_Horizontal.Set_Boolean (False); Orka.Rendering.Textures.Bind (Object.Texture_V, Orka.Rendering.Textures.Texture, 0); Object.Framebuffer_H.Use_Framebuffer; Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3); end loop; GL.Toggles.Enable (GL.Toggles.Depth_Test); end Render; end Orka.Rendering.Effects.Filters;
Fix compiler warning about unreferenced with'ed unit
orka: Fix compiler warning about unreferenced with'ed unit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
9bc596285448301feff08bc20aea9066531df56c
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Events.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Module.Tests; package body AWA.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Events.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Module.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); return Ret; end Suite; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Module.Tests; package body AWA.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Events.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Module.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); return Ret; end Suite; end AWA.Testsuite;
Add unit tests for storages module
Add unit tests for storages module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4ddd2ea3feb7fb2f6494013a5c752016ba7bb238
src/wiki-streams-html-stream.ads
src/wiki-streams-html-stream.ads
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- 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; generic type Output_Stream is limited new Wiki.Streams.Output_Stream with private; package Wiki.Streams.Html.Stream is type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with private; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString); -- Write an optional newline or space. overriding procedure Newline (Writer : in out Html_Output_Stream); private type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 1; Indent_Pos : Natural := 0; Text_Length : Natural := 0; end record; end Wiki.Streams.Html.Stream;
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- 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; generic type Output_Stream is limited new Wiki.Streams.Output_Stream with private; package Wiki.Streams.Html.Stream is type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with private; -- Set the indentation level for HTML output stream. overriding procedure Set_Indent_Level (Writer : in out Html_Output_Stream; Indent : in Natural); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString); -- Write an optional newline or space. overriding procedure Newline (Writer : in out Html_Output_Stream); private type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; Indent_Pos : Natural := 0; Text_Length : Natural := 0; end record; end Wiki.Streams.Html.Stream;
Add Set_Indent_Level procedure
Add Set_Indent_Level procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5faff42e58a960241a51796e65b73a894644802e
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in out Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in out Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ -- procedure Iterate (Doc : in Document; -- Process : not null access procedure (Node : in Node_Type)) is -- Block : Node_List_Block_Access := Doc.Nodes.Value.First'Access; -- begin -- loop -- for I in 1 .. Block.Last loop -- Process (Block.List (I).all); -- end loop; -- Block := Block.Next; -- exit when Block = null; -- end loop; -- end Iterate; -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; end if; end Append; -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- -- overriding -- procedure Initialize (Doc : in out Document) is -- begin -- -- Doc.Nodes := Node_List_Refs.Create; -- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access; -- end Initialize; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in out Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in out Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ -- procedure Iterate (Doc : in Document; -- Process : not null access procedure (Node : in Node_Type)) is -- Block : Node_List_Block_Access := Doc.Nodes.Value.First'Access; -- begin -- loop -- for I in 1 .. Block.Last loop -- Process (Block.List (I).all); -- end loop; -- Block := Block.Next; -- exit when Block = null; -- end loop; -- end Iterate; -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; end Wiki.Nodes;
Fix the Append procedure on a Node_List_Ref
Fix the Append procedure on a Node_List_Ref
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c9fe7a956972e7833a7b8754f598e58e4ac7c01e
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_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; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when N_TAG_END => Tag_End : Html_Tag_Type; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, 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; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Remove the N_TAG_END item
Remove the N_TAG_END item
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5a55e37dbc8a78719d46066a24312f3c9bd73be9
src/core/texts/util-texts-builders.ads
src/core/texts/util-texts-builders.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 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. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Description == -- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an <tt>Append</tt> procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the <tt>Iterate</tt> operation that allows to get the content -- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- == Example == -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the <tt>Iterate</tt> operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- 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); -- 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); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- 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)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 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. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- 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); -- 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); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- 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)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b161321d88c2ac101bfb4f26101fb76378dce47f
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- 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.Exceptions; with Util.Test_Caller; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- 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.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
Implement the Test_Empty_Connection procedure to check various operations on an empty database connection
Implement the Test_Empty_Connection procedure to check various operations on an empty database connection
Ada
apache-2.0
stcarrez/ada-ado
70fe64f117988aa6258047f82f2324895e27b53a
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 Util.Log.Loggers; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.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"); -- Setup the resource bundles. -- Plugin.Manager := Plugin.Create_User_Manager; -- Register.Register (Plugin => Plugin, -- Name => "AWA.Users.Beans.Authenticate_Bean", -- Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- 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;
Implement the Create_Comment and Load_Comment operations
Implement the Create_Comment and Load_Comment operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2ac0b03ca9e48dbf2632c8f5b400fb926bea9cd2
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "34"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "40"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump synth version to 1.40
Bump synth version to 1.40 Starting new cycle based on behavior change of rebuilding repositories.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
ac82f1feca5cd26baead546c233dd0e2527af8c6
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "50"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.24"; default_pgsql : constant String := "9.6"; default_python3 : constant String := "3.5"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_compiler : constant String := "gcc6"; compiler_version : constant String := "6.20170202"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "50"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.24"; default_pgsql : constant String := "9.6"; default_python3 : constant String := "3.5"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_compiler : constant String := "gcc6"; compiler_version : constant String := "6.20170202"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Use the static version of the host pkg8
Use the static version of the host pkg8 We're not going to require the complete pkg(8) in the ravenports metaport.
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
d9703287064571423a6f93e5949074f6151ccaa6
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text)); end Add_Preformatted; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text)); end Add_Preformatted; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
Implement the Is_Visible_TOC function
Implement the Is_Visible_TOC function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9b326e542c60ef72ec94e6255f99a106a40746e1
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa-applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Drivers; with ADO.Sessions.Sources; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with Security.Policies; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is Connection : ADO.Sessions.Sources.Data_Source; begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); Connection.Set_Connection (Conf.Get (P_Database.P)); Connection.Set_Property ("ado.queries.paths", Conf.Get ("ado.queries.paths", "")); Connection.Set_Property ("ado.queries.load", Conf.Get ("ado.queries.load", "")); App.DB_Factory.Create (Connection); App.DB_Factory.Set_Audit_Manager (App.Audits'Unchecked_Access); App.Audits.Initialize (App'Unchecked_Access); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); -- Use a specific error message when the NO_PERMISSION exception is raised. App.Get_Exception_Handler.Set_Message ("AWA.PERMISSIONS.NO_PERMISSION", "layout.exception_no_permission"); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is Manager : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin -- Start the security manager. AWA.Permissions.Services.Permission_Manager'Class (Manager.all).Start; -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
----------------------------------------------------------------------- -- awa-applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Sessions.Sources; with ADO.Configs; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with Security.Policies; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is Connection : ADO.Sessions.Sources.Data_Source; begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ADO.Configs.Initialize (Conf); ASF.Applications.Main.Application (App).Initialize_Config (Conf); Connection.Set_Connection (Conf.Get (P_Database.P)); Connection.Set_Property ("ado.queries.paths", Conf.Get ("ado.queries.paths", "")); Connection.Set_Property ("ado.queries.load", Conf.Get ("ado.queries.load", "")); App.DB_Factory.Create (Connection); App.DB_Factory.Set_Audit_Manager (App.Audits'Unchecked_Access); App.Audits.Initialize (App'Unchecked_Access); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); -- Use a specific error message when the NO_PERMISSION exception is raised. App.Get_Exception_Handler.Set_Message ("AWA.PERMISSIONS.NO_PERMISSION", "layout.exception_no_permission"); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is Manager : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin -- Start the security manager. AWA.Permissions.Services.Permission_Manager'Class (Manager.all).Start; -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
Call ADO.Config.Initialize procedure
Call ADO.Config.Initialize procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b5d97ea982f51f0cb1918ea836659313facb2921
awa/src/awa-index_arrays.ads
awa/src/awa-index_arrays.ads
----------------------------------------------------------------------- -- awa-index_arrays -- Static index arrays -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; generic type Index_Type is range <>; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with function "<" (Left, Right : in Element_Type) return Boolean is <>; with function "&" (Left : in String; Right : in Element_Type) return String is <>; package AWA.Index_Arrays is -- This package must be instantiated for each definition. -- It allocates a unique <tt>Index_Type</tt> value for each definition. generic Name : Element_Type; package Definition is function Kind return Index_Type; pragma Inline_Always (Kind); end Definition; type Element_Type_Access is access constant Element_Type; -- Exception raised if a name is not found. Not_Found : exception; -- Identifies an invalid index. Invalid_Index : constant Index_Type; -- Find the runtime index given the name. -- Raises Not_Found exception if the name is not recognized. function Find (Name : in Element_Type) return Index_Type; -- Get the element associated with the index. function Get_Element (Index : in Index_Type) return Element_Type_Access; -- Check if the index is a valid index. function Is_Valid (Index : in Index_Type) return Boolean; -- Get the last valid index. function Get_Last return Index_Type; private Invalid_Index : constant Index_Type := Index_Type'First; pragma Inline (Is_Valid); pragma Inline (Get_Last); end AWA.Index_Arrays;
----------------------------------------------------------------------- -- awa-index_arrays -- Static index arrays -- 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. ----------------------------------------------------------------------- generic type Index_Type is range <>; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with function "<" (Left, Right : in Element_Type) return Boolean is <>; with function "&" (Left : in String; Right : in Element_Type) return String is <>; package AWA.Index_Arrays is -- This package must be instantiated for each definition. -- It allocates a unique <tt>Index_Type</tt> value for each definition. generic Name : Element_Type; package Definition is function Kind return Index_Type; pragma Inline_Always (Kind); end Definition; type Element_Type_Access is access constant Element_Type; -- Exception raised if a name is not found. Not_Found : exception; -- Identifies an invalid index. Invalid_Index : constant Index_Type; -- Find the runtime index given the name. -- Raises Not_Found exception if the name is not recognized. function Find (Name : in Element_Type) return Index_Type; -- Get the element associated with the index. function Get_Element (Index : in Index_Type) return Element_Type_Access; -- Check if the index is a valid index. function Is_Valid (Index : in Index_Type) return Boolean; -- Get the last valid index. function Get_Last return Index_Type; private Invalid_Index : constant Index_Type := Index_Type'First; pragma Inline (Is_Valid); pragma Inline (Get_Last); end AWA.Index_Arrays;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2c55993d043a6e02f1ac477547b4011fbaeab905
awa/plugins/awa-counters/src/awa-counters-beans.adb
awa/plugins/awa-counters/src/awa-counters-beans.adb
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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.Calendar; with Util.Dates.ISO8601; with ADO.Queries.Loaders; with ADO.Sessions.Entities; with AWA.Services.Contexts; package body AWA.Counters.Beans is package ASC renames AWA.Services.Contexts; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time; function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Name); begin return Util.Beans.Objects.To_Object (From.Value); end Get_Value; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "stats" then return Util.Beans.Objects.To_Object (Value => List.Stats_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Counters.Models.Stat_List_Bean (List).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if not Util.Beans.Objects.Is_Empty (Value) then AWA.Counters.Models.Stat_List_Bean (From).Set_Value (Name, Value); end if; end Set_Value; function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access is Name : constant String := Ada.Strings.Unbounded.To_String (From.Query_Name); begin return ADO.Queries.Loaders.Find_Query (Name); end Get_Query; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time is use type Ada.Calendar.Time; Day : Natural; begin if Date'Length = 0 or Date = "now" then return Now; elsif Date'Length > 5 and then Date (Date'First .. Date'First + 3) = "now-" then Day := Natural'Value (Date (Date'First + 4 .. Date'Last)); return Now - Duration (Day * 86400); else return Util.Dates.ISO8601.Value (Date); end if; end Parse_Date; -- ------------------------------ -- Load the statistics information. -- ------------------------------ overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); use type ADO.Identifier; use type ADO.Queries.Query_Definition_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Def : constant ADO.Queries.Query_Definition_Access := List.Get_Query; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (List.Entity_Type); Session : ADO.Sessions.Session := List.Module.Get_Session; Kind : ADO.Entity_Type; First_Date : Ada.Calendar.Time; Last_Date : Ada.Calendar.Time; Query : ADO.Queries.Context; begin Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); First_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.First_Date), Now); Last_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.Last_Date), Now); if List.Entity_Id /= ADO.NO_IDENTIFIER and Def /= null then Query.Set_Query (Def); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", List.Entity_Id); Query.Bind_Param ("user_id", User); Query.Bind_Param ("first_date", First_Date); Query.Bind_Param ("last_date", Last_Date); Query.Bind_Param ("counter_name", List.Counter_Name); AWA.Counters.Models.List (List.Stats, Session, Query); end if; end Load; -- ------------------------------ -- Create the Blog_Stat_Bean bean instance. -- ------------------------------ function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Counter_Stat_Bean_Access := new Counter_Stat_Bean; begin Object.Module := Module; Object.Stats_Bean := Object.Stats'Access; return Object.all'Access; end Create_Counter_Stat_Bean; end AWA.Counters.Beans;
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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.Calendar; with Util.Dates.ISO8601; with ADO.Queries.Loaders; with ADO.Sessions.Entities; with AWA.Services.Contexts; package body AWA.Counters.Beans is package ASC renames AWA.Services.Contexts; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Name); begin return Util.Beans.Objects.To_Object (From.Value); end Get_Value; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "stats" then return Util.Beans.Objects.To_Object (Value => List.Stats_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Counters.Models.Stat_List_Bean (List).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if not Util.Beans.Objects.Is_Empty (Value) then AWA.Counters.Models.Stat_List_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Get the query definition to collect the counter statistics. -- ------------------------------ function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access is Name : constant String := Ada.Strings.Unbounded.To_String (From.Query_Name); begin return ADO.Queries.Loaders.Find_Query (Name); end Get_Query; function Parse_Date (Date : in String; Now : in Ada.Calendar.Time) return Ada.Calendar.Time is use type Ada.Calendar.Time; Day : Natural; begin if Date'Length = 0 or Date = "now" then return Now; elsif Date'Length > 5 and then Date (Date'First .. Date'First + 3) = "now-" then Day := Natural'Value (Date (Date'First + 4 .. Date'Last)); return Now - Duration (Day * 86400); else return Util.Dates.ISO8601.Value (Date); end if; end Parse_Date; -- ------------------------------ -- Load the statistics information. -- ------------------------------ overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); use type ADO.Identifier; use type ADO.Queries.Query_Definition_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Def : constant ADO.Queries.Query_Definition_Access := List.Get_Query; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (List.Entity_Type); Session : ADO.Sessions.Session := List.Module.Get_Session; Kind : ADO.Entity_Type; First_Date : Ada.Calendar.Time; Last_Date : Ada.Calendar.Time; Query : ADO.Queries.Context; begin Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); First_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.First_Date), Now); Last_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.Last_Date), Now); if List.Entity_Id /= ADO.NO_IDENTIFIER and Def /= null then Query.Set_Query (Def); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", List.Entity_Id); Query.Bind_Param ("user_id", User); Query.Bind_Param ("first_date", First_Date); Query.Bind_Param ("last_date", Last_Date); Query.Bind_Param ("counter_name", List.Counter_Name); AWA.Counters.Models.List (List.Stats, Session, Query); end if; end Load; -- ------------------------------ -- Create the Blog_Stat_Bean bean instance. -- ------------------------------ function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Counter_Stat_Bean_Access := new Counter_Stat_Bean; begin Object.Module := Module; Object.Stats_Bean := Object.Stats'Access; return Object.all'Access; end Create_Counter_Stat_Bean; end AWA.Counters.Beans;
Move the declaration of Get_Query in the package specification
Move the declaration of Get_Query in the package specification
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3074a82fb5027cdb1145169d9d731984e4573a18
mat/src/gtk/mat-targets-gtkmat.ads
mat/src/gtk/mat-targets-gtkmat.ads
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- 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 Gtk.Widget; with Gtkada.Builder; package MAT.Targets.Gtkmat is type Target_Type is new MAT.Targets.Target_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target instance. overriding procedure Initialize (Target : in out Target_Type); -- Initialize the widgets and create the Gtk gui. procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. overriding procedure Interactive (Target : in out Target_Type); private task type Gtk_Loop is entry Start (Target : in Target_Type_Access); end Gtk_Loop; type Target_Type is new MAT.Targets.Target_Type with record Builder : Gtkada.Builder.Gtkada_Builder; Gui_Task : Gtk_Loop; end record; end MAT.Targets.Gtkmat;
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- 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 Gtk.Widget; with Gtkada.Builder; -- with MAT.Consoles.Gtkmat; package MAT.Targets.Gtkmat is type Target_Type is new MAT.Targets.Target_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target instance. overriding procedure Initialize (Target : in out Target_Type); -- Initialize the widgets and create the Gtk gui. procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. overriding procedure Interactive (Target : in out Target_Type); -- Set the UI label with the given value. procedure Set_Label (Target : in Target_Type; Name : in String; Value : in String); private task type Gtk_Loop is entry Start (Target : in Target_Type_Access); end Gtk_Loop; type Target_Type is new MAT.Targets.Target_Type with record Builder : Gtkada.Builder.Gtkada_Builder; Gui_Task : Gtk_Loop; end record; end MAT.Targets.Gtkmat;
Declare the Set_Label procedure
Declare the Set_Label procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
54d2429138b9b864b2c6f5d7c168a7e8b6d1a0f0
mat/src/mat-targets-probes.ads
mat/src/mat-targets-probes.ads
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- 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 MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message); end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- 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 MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); -- Extract the information from the 'library' event. procedure Probe_Library (Probe : in Process_Probe_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Probe_Event_Type); end MAT.Targets.Probes;
Update Probe_Begin and Probe_Library to get and update the Event object
Update Probe_Begin and Probe_Library to get and update the Event object
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
92de7a9e3a8b24ff4600a363459945cf80f2da5f
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Declare the Name_Used exception
Declare the Name_Used exception
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ab63b7a8c4fa00f531706e640c11922e7b94a6a7
regtests/el-objects-time-tests.adb
regtests/el-objects-time-tests.adb
----------------------------------------------------------------------- -- EL.Objects.Time.Tests - Testsuite time objects -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Calendar.Formatting; with Util.Log.Loggers; with Util.Tests; package body EL.Objects.Time.Tests is use Ada.Calendar; use Util.Log; use Util.Tests; LOG : constant Util.Log.Loggers.Logger := Loggers.Create ("Tests"); -- ------------------------------ -- Test evaluation of expression using a bean -- ------------------------------ procedure Test_Time_Object (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); begin T.Assert (Is_Null (V) = False, "Object holding a time value must not be null"); T.Assert (Is_Empty (V) = False, "Object holding a time value must not be empty"); T.Assert (Get_Type (V) = TYPE_TIME, "Object holding a time value must be TYPE_TIME"); T.Assert (C = To_Time (V), "Invalid time returned by To_Time"); end Test_Time_Object; -- ------------------------------ -- Test time to string conversion -- ------------------------------ procedure Test_Time_To_String (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); S : constant EL.Objects.Object := Cast_String (V); V2 : constant EL.Objects.Object := Cast_Time (S); begin -- Both 3 values should be the same. LOG.Info ("Time S : {0}", To_String (S)); LOG.Info ("Time V : {0}", To_String (V)); LOG.Info ("Time V2: {0}", To_String (V2)); Assert_Equals (T, To_String (S), To_String (V), "Invalid time conversion (V)"); Assert_Equals (T, To_String (S), To_String (V2), "Invalid time conversion (V2)"); -- The Cast_String looses accuracy so V and V2 may not be equal. T.Assert (V >= V2, "Invalid time to string conversion"); -- Check the time value taking into account the 1 sec accuracy that was lost. T.Assert (C >= To_Time (V2), "Invalid time returned by To_Time (T > expected)"); T.Assert (C < To_Time (V2) + 1.0, "Invalid time returned by To_Time (T + 1 < expected)"); end Test_Time_To_String; -- ------------------------------ -- Test time add and subtract -- ------------------------------ procedure Test_Time_Add (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); Dt : constant EL.Objects.Object := To_Object (Integer (10)); V2 : constant EL.Objects.Object := V + Dt; V3 : constant EL.Objects.Object := V2 - Dt; begin T.Assert (V3 = V, "Adding and substracting 10 seconds should result in the same time"); T.Assert (V2 > V, "Invalid comparison for time"); T.Assert (V3 < V2, "Invalid comparison for time"); end Test_Time_Add; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - Is_Null, Is_Empty, Get_Type", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - To_Time", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_To_String'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_Add'Access); end Add_Tests; end EL.Objects.Time.Tests;
----------------------------------------------------------------------- -- EL.Objects.Time.Tests - Testsuite time objects -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Calendar.Formatting; with Util.Log.Loggers; with Util.Tests; package body EL.Objects.Time.Tests is use Ada.Calendar; use Util.Log; use Util.Tests; LOG : constant Util.Log.Loggers.Logger := Loggers.Create ("Tests"); -- ------------------------------ -- Test evaluation of expression using a bean -- ------------------------------ procedure Test_Time_Object (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); begin T.Assert (Is_Null (V) = False, "Object holding a time value must not be null"); T.Assert (Is_Empty (V) = False, "Object holding a time value must not be empty"); T.Assert (Get_Type (V) = TYPE_TIME, "Object holding a time value must be TYPE_TIME"); T.Assert (C = To_Time (V), "Invalid time returned by To_Time"); end Test_Time_Object; -- ------------------------------ -- Test time to string conversion -- ------------------------------ procedure Test_Time_To_String (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); S : constant EL.Objects.Object := Cast_String (V); V2 : constant EL.Objects.Object := Cast_Time (S); begin -- Both 3 values should be the same. LOG.Info ("Time S : {0}", To_String (S)); LOG.Info ("Time V : {0}", To_String (V)); LOG.Info ("Time V2: {0}", To_String (V2)); Assert_Equals (T, To_String (S), To_String (V), "Invalid time conversion (V)"); Assert_Equals (T, To_String (S), To_String (V2), "Invalid time conversion (V2)"); -- The Cast_String looses accuracy so V and V2 may not be equal. T.Assert (V >= V2, "Invalid time to string conversion"); -- Check the time value taking into account the 1 sec accuracy that was lost. T.Assert (C >= To_Time (V2), "Invalid time returned by To_Time (T > expected)"); T.Assert (C < To_Time (V2) + 1.0, "Invalid time returned by To_Time (T + 1 < expected)"); end Test_Time_To_String; -- ------------------------------ -- Test time add and subtract -- ------------------------------ procedure Test_Time_Add (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); Dt : constant EL.Objects.Object := To_Object (Integer (10)); V2 : constant EL.Objects.Object := V + Dt; V3 : constant EL.Objects.Object := V2 - Dt; begin T.Assert (V3 = V, "Adding and substracting 10 seconds should result in the same time"); T.Assert (V2 > V, "Invalid comparison for time"); T.Assert (V3 < V2, "Invalid comparison for time"); end Test_Time_Add; package Caller is new Util.Test_Caller (Test, "EL.Objects.Time"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - Is_Null, Is_Empty, Get_Type", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - To_Time", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_To_String'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_Add'Access); end Add_Tests; end EL.Objects.Time.Tests;
Use the test name EL.Objects.Time
Use the test name EL.Objects.Time
Ada
apache-2.0
stcarrez/ada-el
3e9ea1d2fa08081132b95fc09aeba12618a3f941
src/util-streams-buffered.ads
src/util-streams-buffered.ads
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Unchecked_Access, Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : in Output_Stream_Access; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : in Input_Stream_Access; Size : in Positive); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : Output_Stream_Access := null; No_Flush : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : Input_Stream_Access := null; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Unchecked_Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : in Output_Stream_Access; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : in Input_Stream_Access; Size : in Positive); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : Output_Stream_Access := null; No_Flush : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Output_Buffer_Stream); type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : Input_Stream_Access := null; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
563d74aecf4c2599c40e9b08c71dc1875936b6ea
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("Permission is refused because there is no security context"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused by the security controller"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class) is begin if Entity.Is_Null then Log.Debug ("Permission is refused because the entity is null."); raise NO_PERMISSION; end if; Check (Permission, ADO.Objects.Get_Value (Entity.Get_Key)); end Check; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin if Into.Count = MAX_ENTITY_TYPES then raise Util.Serialize.Mappers.Field_Error with "Too many entity types."; end if; Into.Count := Into.Count + 1; Into.Entities (Into.Count) := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entities => Into.Entities); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entities := (others => ADO.NO_ENTITY_TYPE); end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : constant Controller_Config_Access := Policy.Config'Unchecked_Access; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("Permission is refused because there is no security context"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused by the security controller"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class) is begin if Entity.Is_Null then Log.Debug ("Permission is refused because the entity is null."); raise NO_PERMISSION; end if; Check (Permission, ADO.Objects.Get_Value (Entity.Get_Key)); end Check; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin if Into.Count = MAX_ENTITY_TYPES then raise Util.Serialize.Mappers.Field_Error with "Too many entity types."; end if; Into.Count := Into.Count + 1; Into.Entities (Into.Count) := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entities => Into.Entities); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entities := (others => ADO.NO_ENTITY_TYPE); end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : constant Controller_Config_Access := Policy.Config'Unchecked_Access; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e8c7ec95396b1ca6242dc30a88730fa00b840213
awa/src/awa-events-services.adb
awa/src/awa-events-services.adb
----------------------------------------------------------------------- -- 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;
----------------------------------------------------------------------- -- awa-events-services -- AWA Event Manager -- Copyright (C) 2012, 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.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 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;
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
513382a3c3d4ff512208b67d036cc35f28ef92c2
src/asf-servlets-faces-mappers.adb
src/asf-servlets-faces-mappers.adb
----------------------------------------------------------------------- -- asf-servlets-faces-mappers -- Read faces specific configuration files -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Routes.Servlets.Faces; package body ASF.Servlets.Faces.Mappers is use type ASF.Routes.Route_Type_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Routes.Servlets.Faces.Faces_Route_Type'Class, Name => ASF.Routes.Servlets.Faces.Faces_Route_Type_Access); function Find_Servlet (Container : in Servlet_Registry_Access; View : in String) return ASF.Servlets.Servlet_Access is Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View); Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route; begin if Route = null then raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View; end if; if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet"; end if; return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet; end Find_Servlet; -- ------------------------------ -- Save in the servlet config object the value associated with the given field. -- When the URL_MAPPING, URL_PATTERN, VIEW_ID field -- is reached, insert the new configuration rule in the servlet registry. -- ------------------------------ procedure Set_Member (N : in out Servlet_Config; Field : in Servlet_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; Route : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access; begin case Field is when URL_PATTERN => N.URL_Pattern := Value; when VIEW_ID => N.View_Id := Value; when URL_MAPPING => declare View : constant String := To_String (N.View_Id); Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View); begin Route := new ASF.Routes.Servlets.Faces.Faces_Route_Type; Route.View := To_Unbounded_String (View); Route.Servlet := Servlet; N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern), To => Route.all'Access, ELContext => N.Context.all); exception when others => Free (Route); raise; end; end case; end Set_Member; SMapper : aliased Servlet_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("faces-config", SMapper'Access); Reader.Add_Mapping ("module", SMapper'Access); Reader.Add_Mapping ("web-app", SMapper'Access); Config.Handler := Handler; Config.Context := Context; Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin SMapper.Add_Mapping ("url-mapping", URL_MAPPING); SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN); SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID); end ASF.Servlets.Faces.Mappers;
----------------------------------------------------------------------- -- asf-servlets-faces-mappers -- Read faces specific configuration files -- 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 ASF.Routes.Servlets.Faces; package body ASF.Servlets.Faces.Mappers is use type ASF.Routes.Route_Type_Access; function Find_Servlet (Container : in Servlet_Registry_Access; View : in String) return ASF.Servlets.Servlet_Access; function Find_Servlet (Container : in Servlet_Registry_Access; View : in String) return ASF.Servlets.Servlet_Access is Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View); Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route; begin if Route = null then raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View; end if; if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet"; end if; return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet; end Find_Servlet; -- ------------------------------ -- Save in the servlet config object the value associated with the given field. -- When the URL_MAPPING, URL_PATTERN, VIEW_ID field -- is reached, insert the new configuration rule in the servlet registry. -- ------------------------------ procedure Set_Member (N : in out Servlet_Config; Field : in Servlet_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Field is when URL_PATTERN => N.URL_Pattern := Value; when VIEW_ID => N.View_Id := Value; when URL_MAPPING => declare procedure Insert (Route : in out ASF.Routes.Route_Type_Ref); View : constant String := To_String (N.View_Id); Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View); procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is To : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access; begin if Route.Is_Null then To := new ASF.Routes.Servlets.Faces.Faces_Route_Type; To.View := To_Unbounded_String (View); To.Servlet := Servlet; Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access); end if; end Insert; begin N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern), ELContext => N.Context.all, Process => Insert'Access); end; end case; end Set_Member; SMapper : aliased Servlet_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("faces-config", SMapper'Access); Reader.Add_Mapping ("module", SMapper'Access); Reader.Add_Mapping ("web-app", SMapper'Access); Config.Handler := Handler; Config.Context := Context; Servlet_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin SMapper.Add_Mapping ("url-mapping", URL_MAPPING); SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN); SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID); end ASF.Servlets.Faces.Mappers;
Update the route creation to use a Insert procedure for updating the route
Update the route creation to use a Insert procedure for updating the route
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
df84e99a58a3066340429b255963f6c274c39924
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String is begin return Plugin.Module.all.Get_Config (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Module.all.Get_Config (Config); end Get_Config; -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null 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; -- ------------------------------ -- 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 begin if Base /= null then return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base, Name); else return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), "")); end if; end Get_Value; Resolver : aliased Event_ELResolver; Context : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin Context.Set_Resolver (Resolver'Unchecked_Access); return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context), Context); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Context); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String is begin return Plugin.Module.all.Get_Config (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Module.all.Get_Config (Config); end Get_Config; -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Boolean := False) return Boolean is Value : constant String := Plugin.Config.Get (Name, Boolean'Image (Default)); begin if Value in "yes" | "true" | "1" then return True; else return False; end if; exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null 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; -- ------------------------------ -- 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 begin if Base /= null then return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base, Name); else return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), "")); end if; end Get_Value; Resolver : aliased Event_ELResolver; Context : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin Context.Set_Resolver (Resolver'Unchecked_Access); return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context), Context); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Context); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Implement the Get_Config function to retrieve a boolean configuration parameter
Implement the Get_Config function to retrieve a boolean configuration parameter
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fed82cd314f5f40794410477ae607b7ccc4c6181
src/util-commands.adb
src/util-commands.adb
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Characters.Handling; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count > List.Offset then return Count - List.Offset; else return 0; end if; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is pragma Unreferenced (List); begin return Ada.Command_Line.Command_Name; end Get_Command_Name; -- ------------------------------ -- Set the argument list to the given string and split the arguments. -- ------------------------------ procedure Initialize (List : in out String_Argument_List; Line : in String) is First : Natural := Line'First; begin List.Length := Line'Length; List.Line (1 .. Line'Length) := Line; List.Count := 0; loop while First <= Line'Length and then Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; exit when First > Line'Length; List.Start_Pos (List.Count) := First; while First <= Line'Length and then not Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; List.End_Pos (List.Count) := First - 1; List.Count := List.Count + 1; end loop; if List.Count > 0 then List.Count := List.Count - 1; end if; end Initialize; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in String_Argument_List) return Natural is begin return List.Count; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String is begin return List.Line (List.Start_Pos (Pos) .. List.End_Pos (Pos)); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ overriding function Get_Command_Name (List : in String_Argument_List) return String is begin return List.Line (List.Start_Pos (0) .. List.End_Pos (0)); end Get_Command_Name; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Characters.Handling; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count > List.Offset then return Count - List.Offset; else return 0; end if; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is pragma Unreferenced (List); begin return Ada.Command_Line.Command_Name; end Get_Command_Name; -- ------------------------------ -- Set the argument list to the given string and split the arguments. -- ------------------------------ procedure Initialize (List : in out String_Argument_List; Line : in String) is First : Natural := Line'First; begin List.Length := Line'Length; List.Line (1 .. Line'Length) := Line; List.Count := 0; loop while First <= Line'Length and then Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; exit when First > Line'Length; List.Start_Pos (List.Count) := First; while First <= Line'Length and then not Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; List.End_Pos (List.Count) := First - 1; List.Count := List.Count + 1; end loop; if List.Count > 0 then List.Count := List.Count - 1; end if; end Initialize; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in String_Argument_List) return Natural is begin return List.Count; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String is begin return List.Line (List.Start_Pos (Pos) .. List.End_Pos (Pos)); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ overriding function Get_Command_Name (List : in String_Argument_List) return String is begin return List.Line (List.Start_Pos (0) .. List.End_Pos (0)); end Get_Command_Name; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ function Get_Count (List : in Dynamic_Argument_List) return Natural is begin return Natural (List.List.Length); end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String is begin return List.List.Element (Pos); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Dynamic_Argument_List) return String is begin return List.List.Element (1); end Get_Command_Name; end Util.Commands;
Implement Get_Count, Get_Argument, Get_Command_Name for the Dynamic_Argument_List type
Implement Get_Count, Get_Argument, Get_Command_Name for the Dynamic_Argument_List type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a7c626bf7bf3eb5424d63f1d482c0799dd242f39
mat/regtests/mat-memory-tests.adb
mat/regtests/mat-memory-tests.adb
----------------------------------------------------------------------- -- mat-memory-tests -- Unit tests for MAT memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Memory.Targets; package body MAT.Memory.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Memory"); -- Builtin and well known definition of test frames. Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc", Test_Probe_Malloc'Access); Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free", Test_Probe_Free'Access); end Add_Tests; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Probe_Malloc (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Create memory slots: -- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104] for I in 1 .. 10 loop M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S); end loop; -- Search for a memory region that does not overlap a memory slot. M.Find (15, 19, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [15 .. 19]"); M.Find (1, 9, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [1 .. 9]"); M.Find (105, 1000, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [105 .. 1000]"); -- Search with an overlap. M.Find (1, 1000, R); Util.Tests.Assert_Equals (T, 10, Integer (R.Length), "Find must return 10 slots in range [1 .. 1000]"); R.Clear; M.Find (1, 19, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [1 .. 19]"); R.Clear; M.Find (13, 19, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [13 .. 19]"); R.Clear; M.Find (100, 1000, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [100 .. 1000]"); R.Clear; M.Find (101, 1000, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [101 .. 1000]"); end Test_Probe_Malloc; -- ------------------------------ -- Test Probe_Free with update of memory slots. -- ------------------------------ procedure Test_Probe_Free (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Free (10, S); M.Find (1, 1000, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slot after a free"); -- Free the same slot a second time (free error). M.Probe_Free (10, S); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Malloc (20, S); M.Probe_Malloc (30, S); M.Probe_Free (20, S); M.Find (1, 1000, R); Util.Tests.Assert_Equals (T, 2, Integer (R.Length), "Find must return 2 slots after a malloc/free sequence"); end Test_Probe_Free; end MAT.Memory.Tests;
----------------------------------------------------------------------- -- mat-memory-tests -- Unit tests for MAT memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with MAT.Expressions; with MAT.Memory.Targets; package body MAT.Memory.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Memory"); -- Builtin and well known definition of test frames. Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc", Test_Probe_Malloc'Access); Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free", Test_Probe_Free'Access); end Add_Tests; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Probe_Malloc (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Create memory slots: -- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104] for I in 1 .. 10 loop M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S); end loop; -- Search for a memory region that does not overlap a memory slot. M.Find (15, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [15 .. 19]"); M.Find (1, 9, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [1 .. 9]"); M.Find (105, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slots in range [105 .. 1000]"); -- Search with an overlap. M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 10, Integer (R.Length), "Find must return 10 slots in range [1 .. 1000]"); R.Clear; M.Find (1, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [1 .. 19]"); R.Clear; M.Find (13, 19, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [13 .. 19]"); R.Clear; M.Find (100, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [100 .. 1000]"); R.Clear; M.Find (101, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 1, Integer (R.Length), "Find must return 1 slot in range [101 .. 1000]"); end Test_Probe_Malloc; -- ------------------------------ -- Test Probe_Free with update of memory slots. -- ------------------------------ procedure Test_Probe_Free (T : in out Test) is M : MAT.Memory.Targets.Target_Memory; S : Allocation; R : Allocation_Map; begin S.Size := 4; M.Create_Frame (Frame_1_0, S.Frame); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Free (10, S); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 0, Integer (R.Length), "Find must return 0 slot after a free"); -- Free the same slot a second time (free error). M.Probe_Free (10, S); -- Malloc followed by a free. M.Probe_Malloc (10, S); M.Probe_Malloc (20, S); M.Probe_Malloc (30, S); M.Probe_Free (20, S); M.Find (1, 1000, MAT.Expressions.EMPTY, R); Util.Tests.Assert_Equals (T, 2, Integer (R.Length), "Find must return 2 slots after a malloc/free sequence"); end Test_Probe_Free; end MAT.Memory.Tests;
Add the EMPTY expression tree to the Find operation
Add the EMPTY expression tree to the Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1e0f77c85b458fea12547289d4c22cc54c5f4465
demo/texture.adb
demo/texture.adb
-- Simple Lumen demo/test program, using earliest incomplete library. with Ada.Command_Line; with System.Address_To_Access_Conversions; with Lumen.Events.Animate; with Lumen.Image; with Lumen.Window; with GL; with GLU; procedure Texture is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Event : Lumen.Events.Event_Data; Wide : Natural; -- no longer have default values since they're now set by the image size High : Natural; Rotation : Natural := 0; Image : Lumen.Image.Descriptor; Img_Wide : GL.glFloat; Img_High : GL.glFloat; Tx_Name : aliased GL.GLuint; --------------------------------------------------------------------------- Program_Exit : exception; --------------------------------------------------------------------------- -- Create a texture and bind a 2D image to it procedure Create_Texture is use GL; use GLU; package GLB is new System.Address_To_Access_Conversions (GLubyte); IP : GLpointer; begin -- Create_Texture -- Allocate a texture name glGenTextures (1, Tx_Name'Unchecked_Access); -- Bind texture operations to the newly-created texture name glBindTexture (GL_TEXTURE_2D, Tx_Name); -- Select modulate to mix texture with color for shading glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -- Wrap textures at both edges glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -- How the texture behaves when minified and magnified glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -- Create a pointer to the image. This sort of horror show is going to -- be disappearing once Lumen includes its own OpenGL bindings. IP := GLB.To_Pointer (Image.Values (0, 0)'Address).all'Unchecked_Access; -- Build our texture from the image we loaded earlier glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, IP); end Create_Texture; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Size of rectangle upon which image is mapped if Wide > High then Img_Wide := glFloat (1.5); Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide)); else Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High)); Img_High := glFloat (1.5); end if; -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; -- Set up a 3D viewing frustum, which is basically a truncated pyramid -- in which the scene takes place. Roughly, the narrow end is your -- screen, and the wide end is 10 units away from the camera. if W <= H then Aspect := GLdouble (H) / GLdouble (W); glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0); else Aspect := GLdouble (W) / GLdouble (H); glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a black background glClearColor (0.8, 0.8, 0.8, 1.0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- Draw a texture-mapped rectangle with the same aspect ratio as the -- original image glBegin (GL_POLYGON); begin glTexCoord3f (0.0, 1.0, 0.0); glVertex3f (-Img_Wide, -Img_High, 0.0); glTexCoord3f (0.0, 0.0, 0.0); glVertex3f (-Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 0.0, 0.0); glVertex3f ( Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 1.0, 0.0); glVertex3f ( Img_Wide, -Img_High, 0.0); end; glEnd; -- Rotate the object around the Y and Z axes by the current amount, to -- give a "tumbling" effect. glMatrixMode (GL_MODELVIEW); glLoadIdentity; glTranslated (0.0, 0.0, -4.0); glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0); glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_Exit; end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame (Frame_Delta : in Duration) is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Texture -- If we haven't been given an image to work with, just do nothing if Ada.Command_Line.Argument_Count < 1 then raise Program_Exit; end if; -- Read image and use it to size the window. This will suck if your image -- is very large. Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1)); Wide := Image.Width; High := Image.Height; -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Lumen.Window.Create (Win, Name => "Spinning Picture Demo", Width => Wide, Height => High, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Now create the texture and set up to use it Create_Texture; GL.glEnable (GL.GL_TEXTURE_2D); GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name); -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; exception when Program_Exit => null; -- just exit this block, which terminates the app end Texture;
-- Simple Lumen demo/test program, using earliest incomplete library. with Ada.Command_Line; with System.Address_To_Access_Conversions; with Lumen.Events.Animate; with Lumen.Image; with Lumen.Window; with GL; with GLU; procedure Texture is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Direct : Boolean := True; Event : Lumen.Events.Event_Data; Wide : Natural; -- no longer have default values since they're now set by the image size High : Natural; Rotation : Natural := 0; Image : Lumen.Image.Descriptor; Img_Wide : GL.glFloat; Img_High : GL.glFloat; Tx_Name : aliased GL.GLuint; --------------------------------------------------------------------------- Program_Exit : exception; --------------------------------------------------------------------------- -- Create a texture and bind a 2D image to it procedure Create_Texture is use GL; use GLU; package GLB is new System.Address_To_Access_Conversions (GLubyte); IP : GLpointer; begin -- Create_Texture -- Allocate a texture name glGenTextures (1, Tx_Name'Unchecked_Access); -- Bind texture operations to the newly-created texture name glBindTexture (GL_TEXTURE_2D, Tx_Name); -- Select modulate to mix texture with color for shading glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -- Wrap textures at both edges glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -- How the texture behaves when minified and magnified glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -- Create a pointer to the image. This sort of horror show is going to -- be disappearing once Lumen includes its own OpenGL bindings. IP := GLB.To_Pointer (Image.Values (0, 0)'Address).all'Unchecked_Access; -- Build our texture from the image we loaded earlier glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, IP); end Create_Texture; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Size of rectangle upon which image is mapped if Wide > High then Img_Wide := glFloat (1.5); Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide)); else Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High)); Img_High := glFloat (1.5); end if; -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; -- Set up a 3D viewing frustum, which is basically a truncated pyramid -- in which the scene takes place. Roughly, the narrow end is your -- screen, and the wide end is 10 units away from the camera. if W <= H then Aspect := GLdouble (H) / GLdouble (W); glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0); else Aspect := GLdouble (W) / GLdouble (H); glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a black background glClearColor (0.8, 0.8, 0.8, 1.0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- Draw a texture-mapped rectangle with the same aspect ratio as the -- original image glBegin (GL_POLYGON); begin glTexCoord3f (0.0, 1.0, 0.0); glVertex3f (-Img_Wide, -Img_High, 0.0); glTexCoord3f (0.0, 0.0, 0.0); glVertex3f (-Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 0.0, 0.0); glVertex3f ( Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 1.0, 0.0); glVertex3f ( Img_Wide, -Img_High, 0.0); end; glEnd; -- Rotate the object around the Y and Z axes by the current amount, to -- give a "tumbling" effect. glMatrixMode (GL_MODELVIEW); glLoadIdentity; glTranslated (0.0, 0.0, -4.0); glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0); glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_Exit; end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame (Frame_Delta : in Duration) is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Texture -- If we haven't been given an image to work with, just do nothing if Ada.Command_Line.Argument_Count < 1 then raise Program_Exit; end if; -- Read image and use it to size the window. This will suck if your image -- is very large. Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1)); Wide := Image.Width; High := Image.Height; -- If the user provides a second argument, it means "no direct rendering" -- for the OpenGL context if Ada.Command_Line.Argument_Count > 1 then Direct := False; end if; -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Lumen.Window.Create (Win, Name => "Spinning Picture Demo", Width => Wide, Height => High, Direct => Direct, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Now create the texture and set up to use it Create_Texture; GL.glEnable (GL.GL_TEXTURE_2D); GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name); -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; exception when Program_Exit => null; -- just exit this block, which terminates the app end Texture;
Allow a second command-line param, meaning "direct rendering off"
Allow a second command-line param, meaning "direct rendering off"
Ada
isc
darkestkhan/lumen,darkestkhan/lumen2
d2a605ce5e7cfbcac6b23c3f358c9cb948d61598
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; -- ------------------------------ -- 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; -- 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; -- ------------------------------ -- 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;
Declare the Request_Token procedure to get a grant using RFC 6749: 4.3. Resource Owner Password Credentials Grant
Declare the Request_Token procedure to get a grant using RFC 6749: 4.3. Resource Owner Password Credentials Grant
Ada
apache-2.0
stcarrez/ada-security
10076eaf833403383ee15775bfc264122d602d2e
src/util-serialize-io-json.adb
src/util-serialize-io-json.adb
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Streams; with Util.Streams.Buffered; package body Util.Serialize.IO.JSON is use Ada.Strings.Unbounded; -- ----------------------- -- Write the string as a quoted JSON string -- ----------------------- procedure Write_String (Stream : in out Output_Stream; Value : in String) is begin Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("\"""); elsif C = '\' then Stream.Write ("\\"); elsif Character'Pos (C) >= 16#20# then Stream.Write (C); else case C is when Ada.Characters.Latin_1.BS => Stream.Write ("\b"); when Ada.Characters.Latin_1.VT => Stream.Write ("\f"); when Ada.Characters.Latin_1.LF => Stream.Write ("\n"); when Ada.Characters.Latin_1.CR => Stream.Write ("\r"); when Ada.Characters.Latin_1.HT => Stream.Write ("\t"); when others => Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C); end case; end if; end; end loop; Stream.Write ('"'); end Write_String; -- ----------------------- -- Start writing an object identified by the given name -- ----------------------- procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (','); else Current.Has_Fields := True; end if; end if; Node_Info_Stack.Push (Stream.Stack); Current := Node_Info_Stack.Current (Stream.Stack); Current.Has_Fields := False; if Name'Length > 0 then Stream.Write_String (Name); Stream.Write (':'); end if; Stream.Write ('{'); end Start_Entity; -- ----------------------- -- Finish writing an object identified by the given name -- ----------------------- procedure End_Entity (Stream : in out Output_Stream; Name : in String) is pragma Unreferenced (Name); begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write ('}'); end End_Entity; -- ----------------------- -- Write an attribute member from the current object -- ----------------------- procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (","); else Current.Has_Fields := True; end if; end if; Stream.Write_String (Name); Stream.Write (':'); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => Stream.Write ("null"); when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; end Write_Attribute; -- ----------------------- -- Write an object value as an entity -- ----------------------- procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; -- ----------------------- -- Start an array that will contain the specified number of elements -- ----------------------- procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type) is pragma Unreferenced (Length); begin Node_Info_Stack.Push (Stream.Stack); Stream.Write ('['); end Start_Array; -- ----------------------- -- Finishes an array -- ----------------------- procedure End_Array (Stream : in out Output_Stream) is begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write (']'); end End_Array; -- ----------------------- -- Get the current location (file and line) to report an error message. -- ----------------------- function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is -- Put back a token in the buffer. procedure Put_Back (P : in out Parser'Class; Token : in Token_Type); -- Parse the expression buffer to find the next token. procedure Peek (P : in out Parser'Class; Token : out Token_Type); -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null procedure Parse_Pairs (P : in out Parser'Class); -- Parse a value -- value ::= string | number | object | array | true | false | null procedure Parse_Value (P : in out Parser'Class; Name : in String); procedure Parse (P : in out Parser'Class); procedure Parse (P : in out Parser'Class) is Token : Token_Type; begin Peek (P, Token); if Token /= T_LEFT_BRACE then P.Error ("Missing '{'"); end if; Parse_Pairs (P); Peek (P, Token); if Token /= T_RIGHT_BRACE then P.Error ("Missing '}'"); end if; end Parse; -- ------------------------------ -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Pairs (P : in out Parser'Class) is Current_Name : Unbounded_String; Token : Token_Type; begin loop Peek (P, Token); if Token /= T_STRING then Put_Back (P, Token); return; end if; Current_Name := P.Token; Peek (P, Token); if Token /= T_COLON then P.Error ("Missing ':'"); end if; Parse_Value (P, To_String (Current_Name)); Peek (P, Token); if Token /= T_COMMA then Put_Back (P, Token); return; end if; end loop; end Parse_Pairs; -- ------------------------------ -- Parse a value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Value (P : in out Parser'Class; Name : in String) is Token : Token_Type; begin Peek (P, Token); case Token is when T_LEFT_BRACE => P.Start_Object (Name); Parse_Pairs (P); Peek (P, Token); if Token /= T_RIGHT_BRACE then P.Error ("Missing '}'"); end if; P.Finish_Object (Name); -- when T_LEFT_BRACKET => P.Start_Array (Name); Peek (P, Token); if Token /= T_RIGHT_BRACKET then Put_Back (P, Token); loop Parse_Value (P, Name); Peek (P, Token); exit when Token = T_RIGHT_BRACKET; if Token /= T_COMMA then P.Error ("Missing ']'"); end if; end loop; end if; P.Finish_Array (Name); when T_NULL => P.Set_Member (Name, Util.Beans.Objects.Null_Object); when T_NUMBER => P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token)); when T_STRING => P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token)); when T_TRUE => P.Set_Member (Name, Util.Beans.Objects.To_Object (True)); when T_FALSE => P.Set_Member (Name, Util.Beans.Objects.To_Object (False)); when T_EOF => P.Error ("End of stream reached"); return; when others => P.Error ("Invalid token"); end case; end Parse_Value; -- ------------------------------ -- Put back a token in the buffer. -- ------------------------------ procedure Put_Back (P : in out Parser'Class; Token : in Token_Type) is begin P.Pending_Token := Token; end Put_Back; -- ------------------------------ -- Parse the expression buffer to find the next token. -- ------------------------------ procedure Peek (P : in out Parser'Class; Token : out Token_Type) is C, C1 : Character; begin -- If a token was put back, return it. if P.Pending_Token /= T_EOF then Token := P.Pending_Token; P.Pending_Token := T_EOF; return; end if; if P.Has_Pending_Char then C := P.Pending_Char; else -- Skip white spaces loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.LF then P.Line_Number := P.Line_Number + 1; else exit when C /= ' ' and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT; end if; end loop; end if; P.Has_Pending_Char := False; -- See what we have and continue parsing. case C is -- Literal string using double quotes -- Collect up to the end of the string and put -- the result in the parser token result. when '"' => Delete (P.Token, 1, Length (P.Token)); loop Stream.Read (Char => C1); if C1 = '\' then Stream.Read (Char => C1); case C1 is when '"' | '\' | '/' => null; when 'b' => C1 := Ada.Characters.Latin_1.BS; when 'f' => C1 := Ada.Characters.Latin_1.VT; when 'n' => C1 := Ada.Characters.Latin_1.LF; when 'r' => C1 := Ada.Characters.Latin_1.CR; when 't' => C1 := Ada.Characters.Latin_1.HT; when 'u' => null; when others => P.Error ("Invalid character '" & C1 & "' in \x sequence"); end case; elsif C1 = C then Token := T_STRING; return; end if; Append (P.Token, C1); end loop; -- Number when '-' | '0' .. '9' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; if C = '.' then Append (P.Token, C); loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; end if; if C = 'e' or C = 'E' then Append (P.Token, C); Stream.Read (Char => C); if C = '+' or C = '-' then Append (P.Token, C); Stream.Read (Char => C); end if; loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; end if; if C /= ' ' and C /= Ada.Characters.Latin_1.HT then P.Has_Pending_Char := True; P.Pending_Char := C; end if; Token := T_NUMBER; return; -- Parse a name composed of letters or digits. when 'a' .. 'z' | 'A' .. 'Z' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); loop Stream.Read (Char => C); exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z' or C in '0' .. '9' or C = '_'); Append (P.Token, C); end loop; -- Putback the last character unless we can ignore it. if C /= ' ' and C /= Ada.Characters.Latin_1.HT then P.Has_Pending_Char := True; P.Pending_Char := C; end if; -- and empty eq false ge gt le lt ne not null true case Element (P.Token, 1) is when 'n' | 'N' => if P.Token = "null" then Token := T_NULL; return; end if; when 'f' | 'F' => if P.Token = "false" then Token := T_FALSE; return; end if; when 't' | 'T' => if P.Token = "true" then Token := T_TRUE; return; end if; when others => null; end case; Token := T_UNKNOWN; return; when '{' => Token := T_LEFT_BRACE; return; when '}' => Token := T_RIGHT_BRACE; return; when '[' => Token := T_LEFT_BRACKET; return; when ']' => Token := T_RIGHT_BRACKET; return; when ':' => Token := T_COLON; return; when ',' => Token := T_COMMA; return; when others => Token := T_UNKNOWN; return; end case; exception when Ada.IO_Exceptions.Data_Error => Token := T_EOF; return; end Peek; begin Parser'Class (Handler).Start_Object (""); Parse (Handler); Parser'Class (Handler).Finish_Object (""); end Parse; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- 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 Interfaces; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Streams; with Util.Streams.Buffered; package body Util.Serialize.IO.JSON is use Ada.Strings.Unbounded; -- ----------------------- -- Write the string as a quoted JSON string -- ----------------------- procedure Write_String (Stream : in out Output_Stream; Value : in String) is begin Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("\"""); elsif C = '\' then Stream.Write ("\\"); elsif Character'Pos (C) >= 16#20# then Stream.Write (C); else case C is when Ada.Characters.Latin_1.BS => Stream.Write ("\b"); when Ada.Characters.Latin_1.VT => Stream.Write ("\f"); when Ada.Characters.Latin_1.LF => Stream.Write ("\n"); when Ada.Characters.Latin_1.CR => Stream.Write ("\r"); when Ada.Characters.Latin_1.HT => Stream.Write ("\t"); when others => Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C); end case; end if; end; end loop; Stream.Write ('"'); end Write_String; -- ----------------------- -- Start writing an object identified by the given name -- ----------------------- procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (','); else Current.Has_Fields := True; end if; end if; Node_Info_Stack.Push (Stream.Stack); Current := Node_Info_Stack.Current (Stream.Stack); Current.Has_Fields := False; if Name'Length > 0 then Stream.Write_String (Name); Stream.Write (':'); end if; Stream.Write ('{'); end Start_Entity; -- ----------------------- -- Finish writing an object identified by the given name -- ----------------------- procedure End_Entity (Stream : in out Output_Stream; Name : in String) is pragma Unreferenced (Name); begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write ('}'); end End_Entity; -- ----------------------- -- Write an attribute member from the current object -- ----------------------- procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack); begin if Current /= null then if Current.Has_Fields then Stream.Write (","); else Current.Has_Fields := True; end if; end if; Stream.Write_String (Name); Stream.Write (':'); case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => Stream.Write ("null"); when TYPE_BOOLEAN => if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); when others => Stream.Write_String (Util.Beans.Objects.To_String (Value)); end case; end Write_Attribute; -- ----------------------- -- Write an object value as an entity -- ----------------------- procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; -- ----------------------- -- Start an array that will contain the specified number of elements -- ----------------------- procedure Start_Array (Stream : in out Output_Stream; Length : in Ada.Containers.Count_Type) is pragma Unreferenced (Length); begin Node_Info_Stack.Push (Stream.Stack); Stream.Write ('['); end Start_Array; -- ----------------------- -- Finishes an array -- ----------------------- procedure End_Array (Stream : in out Output_Stream) is begin Node_Info_Stack.Pop (Stream.Stack); Stream.Write (']'); end End_Array; -- ----------------------- -- Get the current location (file and line) to report an error message. -- ----------------------- function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is -- Put back a token in the buffer. procedure Put_Back (P : in out Parser'Class; Token : in Token_Type); -- Parse the expression buffer to find the next token. procedure Peek (P : in out Parser'Class; Token : out Token_Type); function Hexdigit (C : in Character) return Interfaces.Unsigned_32; -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null procedure Parse_Pairs (P : in out Parser'Class); -- Parse a value -- value ::= string | number | object | array | true | false | null procedure Parse_Value (P : in out Parser'Class; Name : in String); procedure Parse (P : in out Parser'Class); procedure Parse (P : in out Parser'Class) is Token : Token_Type; begin Peek (P, Token); if Token /= T_LEFT_BRACE then P.Error ("Missing '{'"); end if; Parse_Pairs (P); Peek (P, Token); if Token /= T_RIGHT_BRACE then P.Error ("Missing '}'"); end if; end Parse; -- ------------------------------ -- Parse a list of members -- members ::= pair | pair ',' members -- pair ::= string ':' value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Pairs (P : in out Parser'Class) is Current_Name : Unbounded_String; Token : Token_Type; begin loop Peek (P, Token); if Token /= T_STRING then Put_Back (P, Token); return; end if; Current_Name := P.Token; Peek (P, Token); if Token /= T_COLON then P.Error ("Missing ':'"); end if; Parse_Value (P, To_String (Current_Name)); Peek (P, Token); if Token /= T_COMMA then Put_Back (P, Token); return; end if; end loop; end Parse_Pairs; function Hexdigit (C : in Character) return Interfaces.Unsigned_32 is use type Interfaces.Unsigned_32; begin if C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); elsif C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; else raise Constraint_Error with "Invalid hexdigit: " & C; end if; end Hexdigit; -- ------------------------------ -- Parse a value -- value ::= string | number | object | array | true | false | null -- ------------------------------ procedure Parse_Value (P : in out Parser'Class; Name : in String) is Token : Token_Type; begin Peek (P, Token); case Token is when T_LEFT_BRACE => P.Start_Object (Name); Parse_Pairs (P); Peek (P, Token); if Token /= T_RIGHT_BRACE then P.Error ("Missing '}'"); end if; P.Finish_Object (Name); -- when T_LEFT_BRACKET => P.Start_Array (Name); Peek (P, Token); if Token /= T_RIGHT_BRACKET then Put_Back (P, Token); loop Parse_Value (P, Name); Peek (P, Token); exit when Token = T_RIGHT_BRACKET; if Token /= T_COMMA then P.Error ("Missing ']'"); end if; end loop; end if; P.Finish_Array (Name); when T_NULL => P.Set_Member (Name, Util.Beans.Objects.Null_Object); when T_NUMBER => P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token)); when T_STRING => P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token)); when T_TRUE => P.Set_Member (Name, Util.Beans.Objects.To_Object (True)); when T_FALSE => P.Set_Member (Name, Util.Beans.Objects.To_Object (False)); when T_EOF => P.Error ("End of stream reached"); return; when others => P.Error ("Invalid token"); end case; end Parse_Value; -- ------------------------------ -- Put back a token in the buffer. -- ------------------------------ procedure Put_Back (P : in out Parser'Class; Token : in Token_Type) is begin P.Pending_Token := Token; end Put_Back; -- ------------------------------ -- Parse the expression buffer to find the next token. -- ------------------------------ procedure Peek (P : in out Parser'Class; Token : out Token_Type) is C, C1 : Character; begin -- If a token was put back, return it. if P.Pending_Token /= T_EOF then Token := P.Pending_Token; P.Pending_Token := T_EOF; return; end if; if P.Has_Pending_Char then C := P.Pending_Char; else -- Skip white spaces loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.LF then P.Line_Number := P.Line_Number + 1; else exit when C /= ' ' and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT; end if; end loop; end if; P.Has_Pending_Char := False; -- See what we have and continue parsing. case C is -- Literal string using double quotes -- Collect up to the end of the string and put -- the result in the parser token result. when '"' => Delete (P.Token, 1, Length (P.Token)); loop Stream.Read (Char => C1); if C1 = '\' then Stream.Read (Char => C1); case C1 is when '"' | '\' | '/' => null; when 'b' => C1 := Ada.Characters.Latin_1.BS; when 'f' => C1 := Ada.Characters.Latin_1.VT; when 'n' => C1 := Ada.Characters.Latin_1.LF; when 'r' => C1 := Ada.Characters.Latin_1.CR; when 't' => C1 := Ada.Characters.Latin_1.HT; when 'u' => declare use Interfaces; C2, C3, C4 : Character; Val : Interfaces.Unsigned_32; begin Stream.Read (Char => C1); Stream.Read (Char => C2); Stream.Read (Char => C3); Stream.Read (Char => C4); Val := Interfaces.Shift_Left (Hexdigit (C1), 12); Val := Val + Interfaces.Shift_Left (Hexdigit (C2), 8); Val := Val + Interfaces.Shift_Left (Hexdigit (C3), 4); Val := Val + Hexdigit (C4); -- Encode the value as an UTF-8 string. if Val >= 16#1000# then Append (P.Token, Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0fff#; Append (P.Token, Character'Val (16#80# or Shift_Right (Val, 6))); Val := Val and 16#03f#; C1 := Character'Val (16#80# or Val); elsif Val >= 16#80# then Append (P.Token, Character'Val (16#C0# or Shift_Right (Val, 6))); Val := Val and 16#03f#; C1 := Character'Val (16#80# or Val); else C1 := Character'Val (Val); end if; end; when others => P.Error ("Invalid character '" & C1 & "' in \x sequence"); end case; elsif C1 = C then Token := T_STRING; return; end if; Append (P.Token, C1); end loop; -- Number when '-' | '0' .. '9' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; if C = '.' then Append (P.Token, C); loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; end if; if C = 'e' or C = 'E' then Append (P.Token, C); Stream.Read (Char => C); if C = '+' or C = '-' then Append (P.Token, C); Stream.Read (Char => C); end if; loop Stream.Read (Char => C); exit when C not in '0' .. '9'; Append (P.Token, C); end loop; end if; if C /= ' ' and C /= Ada.Characters.Latin_1.HT then P.Has_Pending_Char := True; P.Pending_Char := C; end if; Token := T_NUMBER; return; -- Parse a name composed of letters or digits. when 'a' .. 'z' | 'A' .. 'Z' => Delete (P.Token, 1, Length (P.Token)); Append (P.Token, C); loop Stream.Read (Char => C); exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z' or C in '0' .. '9' or C = '_'); Append (P.Token, C); end loop; -- Putback the last character unless we can ignore it. if C /= ' ' and C /= Ada.Characters.Latin_1.HT then P.Has_Pending_Char := True; P.Pending_Char := C; end if; -- and empty eq false ge gt le lt ne not null true case Element (P.Token, 1) is when 'n' | 'N' => if P.Token = "null" then Token := T_NULL; return; end if; when 'f' | 'F' => if P.Token = "false" then Token := T_FALSE; return; end if; when 't' | 'T' => if P.Token = "true" then Token := T_TRUE; return; end if; when others => null; end case; Token := T_UNKNOWN; return; when '{' => Token := T_LEFT_BRACE; return; when '}' => Token := T_RIGHT_BRACE; return; when '[' => Token := T_LEFT_BRACKET; return; when ']' => Token := T_RIGHT_BRACKET; return; when ':' => Token := T_COLON; return; when ',' => Token := T_COMMA; return; when others => Token := T_UNKNOWN; return; end case; exception when Ada.IO_Exceptions.Data_Error => Token := T_EOF; return; end Peek; begin Parser'Class (Handler).Start_Object (""); Parse (Handler); Parser'Class (Handler).Finish_Object (""); end Parse; end Util.Serialize.IO.JSON;
Handle the JSON \u sequences and emit UTF-8 strings
Handle the JSON \u sequences and emit UTF-8 strings
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4d104cc33ef6fb4fc8fed1f5a742984d3abb6c04
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Sessions; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use type ADO.Sessions.Connection_Status; C : ADO.Sessions.Session; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (C.Get_Status = ADO.Sessions.CLOSED, "The database connection must be closed for an empty connection"); -- Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), -- "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement (""); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := C.Create_Statement ("select"); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. -- begin -- T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); -- exception -- when ADO.Sessions.NOT_OPEN => -- null; -- end; end Test_Empty_Connection; end ADO.Drivers.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/ada-ado
4ce81654fc87465f1a19526186856896cb18cf73
src/os-linux/util-streams-raw.ads
src/os-linux/util-streams-raw.ads
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 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.Finalization; with Util.Systems.Os; with Util.Systems.Types; -- === Raw files === -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>read</b> and <b>write</b>. package Util.Streams.Raw is -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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); private use Ada.Streams; -- Flush the stream and release the buffer. procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 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.Finalization; with Util.Systems.Os; with Util.Systems.Types; -- == Raw files == -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>read</b> and <b>write</b>. package Util.Streams.Raw is -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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); private use Ada.Streams; -- Flush the stream and release the buffer. procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
Add and update the documentation
Add and update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3e6d974eea723ebe194c8d82fb85b6987863ab1c
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for 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.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (DATABASE)", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (FILE)", Test_File_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Get_Local_File", Test_Get_Local_File'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); Store.Set_Mime_Type ("text/plain"); Store.Set_Name ("Makefile"); Store.Set_File_Size (1000); T.Manager.Save (Into => Store, Path => "Makefile", Storage => T.Kind); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; procedure Test_File_Create_Storage (T : in out Test) is begin T.Kind := AWA.Storages.Models.FILE; T.Test_Create_Storage; end Test_File_Create_Storage; -- ------------------------------ -- Test creation of a storage object and local file access after its creation. -- ------------------------------ procedure Test_Get_Local_File (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; declare File : AWA.Storages.Storage_File; begin T.Manager.Get_Local_File (From => T.Id, Into => File); T.Assert (AWA.Storages.Get_Path (File)'Length > 0, "Invalid local file path"); end; end Test_Get_Local_File; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); begin T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (False, "No exception raised"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; Upload : AWA.Storages.Beans.Factories.Upload_Bean; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Upload.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Test folder name"); Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key)); Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name), "Invalid folder name"); end Test_Create_Folder; end AWA.Storages.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- 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.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (DATABASE)", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (FILE)", Test_File_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean", Test_Create_Folder'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Get_Local_File", Test_Get_Local_File'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); Store.Set_Mime_Type ("text/plain"); Store.Set_Name ("Makefile"); Store.Set_File_Size (1000); T.Manager.Save (Into => Store, Path => "Makefile", Storage => T.Kind); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; procedure Test_File_Create_Storage (T : in out Test) is begin T.Kind := AWA.Storages.Models.FILE; T.Test_Create_Storage; end Test_File_Create_Storage; -- ------------------------------ -- Test creation of a storage object and local file access after its creation. -- ------------------------------ procedure Test_Get_Local_File (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; declare File : AWA.Storages.Storage_File (AWA.Storages.TMP); begin T.Manager.Get_Local_File (From => T.Id, Into => File); T.Assert (AWA.Storages.Get_Path (File)'Length > 0, "Invalid local file path"); end; end Test_Get_Local_File; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; Name : Ada.Strings.Unbounded.Unbounded_String; Mime : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); begin T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data); T.Assert (False, "No exception raised"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Storage; -- ------------------------------ -- Test creation of a storage folder -- ------------------------------ procedure Test_Create_Folder (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Factories.Folder_Bean; Outcome : Ada.Strings.Unbounded.Unbounded_String; Upload : AWA.Storages.Beans.Factories.Upload_Bean; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Upload.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Test folder name"); Folder.Save (Outcome); Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action"); Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key)); Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name), "Invalid folder name"); end Test_Create_Folder; end AWA.Storages.Services.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
2919f2194ba70b2e45a638ab23710a943dc50890
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 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. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Documents.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List (Document, Level, Ordered); else Document.Add_List (Level, Ordered); end if; end Add_List; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Add_Row (Document); else Document.Add_Row; end if; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Column (Document, Attributes); else Document.Add_Column (Attributes); end if; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish_Table (Document); else Document.Finish_Table; end if; end Finish_Table; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 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. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Documents.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Definition : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Definition (Document, Definition); else Wiki.Documents.Add_Definition (Document, Definition); end if; end Add_Definition; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List (Document, Level, Ordered); else Document.Add_List (Level, Ordered); end if; end Add_List; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Add_Row (Document); else Document.Add_Row; end if; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Column (Document, Attributes); else Document.Add_Column (Attributes); end if; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish_Table (Document); else Document.Finish_Table; end if; end Finish_Table; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
Implement the Add_Definition procedure
Implement the Add_Definition procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
eb77cb9c203fad2e549697b41a9c8729e554fb8f
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; type Plugin_Factory is limited Interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; end record; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited Interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
19675c907b049cae7ac68358366648d0f354b4fc
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- 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.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- 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 is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- 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) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- 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.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- 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 is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- 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) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("mat>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Change the prompt to 'mat>'
Change the prompt to 'mat>'
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f96c24ae24f7a7c8db7d20f5708e3fa83810944b
src/util-streams-files.ads
src/util-streams-files.ads
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type File_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
Fix compilation error with GNAT 2015
Fix compilation error with GNAT 2015
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cc8731368924881f96a9bc1cebd6201f1a418f16
src/wiki-plugins-templates.adb
src/wiki-plugins-templates.adb
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Directories; with Wiki.Parsers; with Wiki.Streams.Text_IO; package body Wiki.Plugins.Templates is use Ada.Strings.Unbounded; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is P : Wiki.Parsers.Parser; Content : Wiki.Strings.UString; begin Template_Plugin'Class (Plugin).Get_Template (Params, Content); P.Set_Context (Context); P.Parse (Content, Document); end Expand; -- ------------------------------ -- Find a plugin knowing its name. -- ------------------------------ overriding function Find (Factory : in File_Template_Plugin; Name : in String) return Wiki_Plugin_Access is Path : constant String := Ada.Directories.Compose (To_String (Factory.Path), Name); begin if Ada.Directories.Exists (Path) then return Factory'Unrestricted_Access; else return null; end if; end Find; -- ------------------------------ -- Set the directory path that contains template files. -- ------------------------------ procedure Set_Template_Path (Plugin : in out File_Template_Plugin; Path : in String) is begin Plugin.Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end Set_Template_Path; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- Read the file whose basename correspond to the first parameter and parse that file -- in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out File_Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is First : constant Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Name : constant String := Wiki.Attributes.Get_Value (First); Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; P : Wiki.Parsers.Parser; Path : constant String := Ada.Directories.Compose (To_String (Plugin.Path), Name); begin Input.Open (Path, "WCEM=8"); P.Set_Context (Context); P.Parse (Input'Unchecked_Access, Document); Input.Close; exception when Ada.IO_Exceptions.Name_Error => null; end Expand; end Wiki.Plugins.Templates;
----------------------------------------------------------------------- -- wiki-plugins-template -- Template Plugin -- Copyright (C) 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.IO_Exceptions; with Ada.Directories; with Wiki.Parsers; with Wiki.Streams.Text_IO; package body Wiki.Plugins.Templates is use Ada.Strings.Unbounded; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- The <tt>Get_Template</tt> operation is called and the template content returned -- by that operation is parsed in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is P : Wiki.Parsers.Parser; Content : Wiki.Strings.UString; begin Template_Plugin'Class (Plugin).Get_Template (Params, Content); P.Set_Context (Context); P.Parse (Content, Document); end Expand; -- ------------------------------ -- Find a plugin knowing its name. -- ------------------------------ overriding function Find (Factory : in File_Template_Plugin; Name : in String) return Wiki_Plugin_Access is Path : constant String := Ada.Directories.Compose (To_String (Factory.Path), Name); begin if Ada.Directories.Exists (Path) then return Factory'Unrestricted_Access; else return null; end if; end Find; -- ------------------------------ -- Set the directory path that contains template files. -- ------------------------------ procedure Set_Template_Path (Plugin : in out File_Template_Plugin; Path : in String) is begin Plugin.Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end Set_Template_Path; -- ------------------------------ -- Expand the template configured with the parameters for the document. -- Read the file whose basename correspond to the first parameter and parse that file -- in the current document. Template parameters are passed -- in the <tt>Context</tt> instance and they can be evaluated within the template -- while parsing the template content. -- ------------------------------ overriding procedure Expand (Plugin : in out File_Template_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is First : constant Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Name : constant String := Wiki.Attributes.Get_Value (First); Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; P : Wiki.Parsers.Parser; Path : constant String := Ada.Directories.Compose (To_String (Plugin.Path), Name); begin Input.Open (Path, "WCEM=8"); P.Set_Context (Context); P.Parse (Input'Unchecked_Access, Document); Input.Close; exception when Ada.IO_Exceptions.Name_Error => null; end Expand; end Wiki.Plugins.Templates;
Change the Context parameter to 'in out' because we may need to access the filters
Change the Context parameter to 'in out' because we may need to access the filters
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
7d66c19d54241f9954c68578cbc016ed0ea03c8c
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_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 : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_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 : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_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 : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns true if the column is using a variable length (ex: a string). function Is_Variable_Length (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_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 : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Declare Is_Variable_Length function to check if a column is using a variable length type
Declare Is_Variable_Length function to check if a column is using a variable length type
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
679a7af07b352337708155106110edb89e751c2b
src/babel-files-maps.adb
src/babel-files-maps.adb
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Type is Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if File_Maps.Has_Element (Pos) then return File_Maps.Element (Pos); else return NO_FILE; end if; end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Type is Pos : constant Directory_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if Directory_Maps.Has_Element (Pos) then return Directory_Maps.Element (Pos); else return NO_DIRECTORY; end if; end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Type is Pos : constant File_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if File_Maps.Has_Element (Pos) then return File_Maps.Element (Pos); else return NO_FILE; end if; end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Find the directory with the given name in the directory map. -- ------------------------------ function Find (From : in Directory_Map; Name : in String) return Directory_Type is Pos : constant Directory_Cursor := From.Find (Key => Name'Unrestricted_Access); begin if Directory_Maps.Has_Element (Pos) then return Directory_Maps.Element (Pos); else return NO_DIRECTORY; end if; end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Known_Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Known_Dirs, Name); end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type) is begin Default_Container (Into).Set_Directory (Directory); Into.Known_Files.Clear; Into.Known_Dirs.Clear; end Set_Directory; -- ------------------------------ -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. -- ------------------------------ procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)) is begin Update (Container.Known_Files, Container.Known_Dirs); end Prepare; end Babel.Files.Maps;
Add overriding to the methods on Differential_Container type
Add overriding to the methods on Differential_Container type
Ada
apache-2.0
stcarrez/babel
a148eee2c6dda3083c1c59fedca5e01597d810bc
src/babel-files-maps.ads
src/babel-files-maps.ads
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Type; -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Type; type Differential_Container is new Babel.Files.Default_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type); -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)); private type Differential_Container is new Babel.Files.Default_Container with record Known_Files : File_Map; Known_Dirs : Directory_Map; end record; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Type; -- Insert the file in the file map. procedure Insert (Into : in out File_Map; File : in File_Type); -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Type; type Differential_Container is new Babel.Files.Default_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type); -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)); private type Differential_Container is new Babel.Files.Default_Container with record Known_Files : File_Map; Known_Dirs : Directory_Map; end record; end Babel.Files.Maps;
Define the Insert procedure to insert a new File_Type in the map
Define the Insert procedure to insert a new File_Type in the map
Ada
apache-2.0
stcarrez/babel
498a732081c55dfea82a1929d59f6a92fc6efb72
src/ado-configs.ads
src/ado-configs.ads
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
----------------------------------------------------------------------- -- ado-configs -- Database connection configuration -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Properties; package ADO.Configs is -- Configuration property to control the search paths to load XML queries. QUERY_PATHS_CONFIG : constant String := "ado.queries.paths"; -- Configuration property to control whether all the program XML queries must be -- loaded when the database configuration is setup. QUERY_LOAD_CONFIG : constant String := "ado.queries.load"; -- Configuration property to enable or disable the dynamic load of database driver. DYNAMIC_DRIVER_LOAD : constant String := "ado.drivers.load"; -- Configuration property to skip reading the database table entities. NO_ENTITY_LOAD : constant String := "ado.entities.ignore"; -- Raised when the connection URI is invalid. Connection_Error : exception; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Config : in out Configuration; URI : in String); -- Get the connection URI that describes the database connection string. -- The returned string may contain connection authentication information. function Get_URI (Config : in Configuration) return String; -- Get the connection URI that describes the database connection string -- but the connection authentication is replaced by XXXX. function Get_Log_URI (Config : in Configuration) return String; -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Config : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Config : in Configuration; Name : in String) return String; -- Returns true if the configuration property is set to true/on. function Is_On (Config : in Configuration; Name : in String) return Boolean; -- Set the server hostname. procedure Set_Server (Config : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Config : in Configuration) return String; -- Set the server port. procedure Set_Port (Config : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Config : in Configuration) return Natural; -- Set the database name. procedure Set_Database (Config : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Config : in Configuration) return String; -- Get the database driver name. function Get_Driver (Config : in Configuration) return String; -- Iterate over the configuration properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Config : in Configuration; Process : access procedure (Name : in String; Item : in Util.Properties.Value)); private use Ada.Strings.Unbounded; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String; Log_URI : Unbounded_String; Driver : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : Unbounded_String; Properties : Util.Properties.Manager; end record; end ADO.Configs;
Declare Is_On function and NO_ENTITY_LOAD constant
Declare Is_On function and NO_ENTITY_LOAD constant
Ada
apache-2.0
stcarrez/ada-ado
0c11e391d66a56bac91d491bf34d8cedcf885355
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Implement the Get_User operation
Implement the Get_User operation
Ada
apache-2.0
stcarrez/babel
4f72ccc44d9e811da09096a824402b662980eda6
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File) return Boolean is begin return Element.Status /= FILE_UNCHANGED; end Is_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Compute_Sha1 (Path : in String; Into : in out File) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Name : constant String := Path & "/" & To_String (Into.Name); Last : Ada.Streams.Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (0 .. 32_767); Ctx : Util.Encoders.SHA1.Context; begin Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name); loop Ada.Streams.Stream_IO.Read (File, Buf, Last); Util.Encoders.SHA1.Update (Ctx, Buf (Buf'First .. Last)); exit when Last /= Buf'Last; end loop; Ada.Streams.Stream_IO.Close (File); Util.Encoders.SHA1.Finish (Ctx, Into.SHA1); end Compute_Sha1; procedure Iterate_Files (Path : in String; Dir : in out Directory; Depth : in Natural; Update : access procedure (P : in String; F : in out File)) is use Ada.Strings.Unbounded; Iter : File_Vectors.Cursor := Dir.Files.First; procedure Iterate_File (Item : in out File) is begin Update (Path, Item); end Iterate_File; procedure Iterate_Child (Item : in out Directory) is begin Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update); end Iterate_Child; begin while File_Vectors.Has_Element (Iter) loop Dir.Files.Update_Element (Iter, Iterate_File'Access); File_Vectors.Next (Iter); end loop; if Depth > 0 and then Dir.Children /= null then declare Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First; begin while Directory_Vectors.Has_Element (Dir_Iter) loop Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access); Directory_Vectors.Next (Dir_Iter); end loop; end; end if; end Iterate_Files; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Compute_Sha1 (Path : in String; Into : in out File) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Name : constant String := Path & "/" & To_String (Into.Name); Last : Ada.Streams.Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (0 .. 32_767); Ctx : Util.Encoders.SHA1.Context; begin Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name); loop Ada.Streams.Stream_IO.Read (File, Buf, Last); Util.Encoders.SHA1.Update (Ctx, Buf (Buf'First .. Last)); exit when Last /= Buf'Last; end loop; Ada.Streams.Stream_IO.Close (File); Util.Encoders.SHA1.Finish (Ctx, Into.SHA1); end Compute_Sha1; procedure Iterate_Files (Path : in String; Dir : in out Directory; Depth : in Natural; Update : access procedure (P : in String; F : in out File)) is use Ada.Strings.Unbounded; Iter : File_Vectors.Cursor := Dir.Files.First; procedure Iterate_File (Item : in out File) is begin Update (Path, Item); end Iterate_File; procedure Iterate_Child (Item : in out Directory) is begin Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update); end Iterate_Child; begin while File_Vectors.Has_Element (Iter) loop Dir.Files.Update_Element (Iter, Iterate_File'Access); File_Vectors.Next (Iter); end loop; if Depth > 0 and then Dir.Children /= null then declare Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First; begin while Directory_Vectors.Has_Element (Dir_Iter) loop Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access); Directory_Vectors.Next (Dir_Iter); end loop; end; end if; end Iterate_Files; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
Fix the Is_Modified operation to use the new Status_Type
Fix the Is_Modified operation to use the new Status_Type
Ada
apache-2.0
stcarrez/babel
d72c6774b66d34661b08d437fcf26692b1e6f7e2
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "53"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "54"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump version
Bump version
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
67dd28110d63a9d0eb65cd8623ac9deb8ac2551c
src/gen-commands-project.ads
src/gen-commands-project.ads
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- 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 Gen.Commands.Project is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Project is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Project;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9dda4f8777b6bb7450e6eac6b588418511612742
src/natools-web-comments.ads
src/natools-web-comments.ads
------------------------------------------------------------------------------ -- Copyright (c) 2015-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Comments provides an implementation of user-posted comments -- -- like is commonly found on blogs. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Printers; with Natools.Web.Sites; with Natools.Web.Tags; private with Ada.Calendar.Time_Zones; private with Ada.Containers.Doubly_Linked_Lists; private with Ada.Finalization; private with Natools.Constant_Indefinite_Ordered_Maps; private with Natools.References; private with Natools.Storage_Pools; private with Natools.Web.Containers; private with Natools.Web.Sites.Updates; package Natools.Web.Comments is type Comment_Ref is new Tags.Visible with private; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Comment_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- Render a comment type Comment_List is tagged private; procedure Load (Object : in out Comment_List; Builder : in out Sites.Site_Builder; Parent : in Tags.Visible_Access := null; Parent_Path : in S_Expressions.Atom_Refs.Immutable_Reference := S_Expressions.Atom_Refs.Null_Immutable_Reference); -- Load comment list from Builder back-end and register all comments procedure Render (Exchange : in out Sites.Exchange; Object : in Comment_List; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- Render a comment list procedure Respond (List : in out Comment_List; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom); -- Respond to a request for the comment list procedure Set (List : out Comment_List; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize List using data from Expression private package Comment_Atoms is type Enum is (Name, Mail, Link, Text, Class, Note, Title, Filter); type Set is array (Enum) of S_Expressions.Atom_Refs.Immutable_Reference; end Comment_Atoms; package Comment_Flags is type Enum is (Preprocessed, Ignored); type Set is array (Enum) of Boolean with Pack; end Comment_Flags; package List_Flags is type Enum is (Ignore_By_Default, Allow_Date_Override, Closed, Allow_Ignore); type Set is array (Enum) of Boolean with Pack; end List_Flags; type Comment_Data is record Date : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; Id : S_Expressions.Atom_Refs.Immutable_Reference; Atoms : Comment_Atoms.Set; Flags : Comment_Flags.Set := (others => False); Parent : Tags.Visible_Access; Rank : Positive; end record; procedure Preprocess (Comment : in out Comment_Data; List : in Comment_List; Site : in Sites.Site); procedure Preprocess (Comment : in out Comment_Data; List : in Comment_List; Builder : in Sites.Site_Builder); -- Preprocess comment field contents procedure Write (Comment : in Comment_Data; Output : in out S_Expressions.Printers.Printer'Class); -- Serialize a comment into the given S_Expression stream package Comment_Maps is new Natools.Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Comment_Data, S_Expressions."<"); procedure Set_Parent (Container : in out Comment_Maps.Updatable_Map; Parent : in Tags.Visible_Access); procedure Update_Ranks (Container : in out Comment_Maps.Updatable_Map); protected type Comment_Container is procedure Initialize (Data : in Comment_Maps.Unsafe_Maps.Map; Parent : in Tags.Visible_Access); procedure Insert (Data : in Comment_Data); procedure Ignore (Id : in S_Expressions.Atom; Ref : out S_Expressions.Atom_Refs.Immutable_Reference); procedure Orphan; function Find (Id : S_Expressions.Atom_Refs.Immutable_Reference) return Comment_Maps.Cursor; function First return Comment_Maps.Cursor; function Iterate return Comment_Maps.Map_Iterator_Interfaces.Reversible_Iterator'Class; function Length return Natural; private Map : Comment_Maps.Updatable_Map; Parent : Tags.Visible_Access; end Comment_Container; package Container_Refs is new References (Comment_Container, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); type Comment_Ref is new Tags.Visible with record Container : Container_Refs.Reference; Id : S_Expressions.Atom_Refs.Immutable_Reference; end record; type Comment_List is new Ada.Finalization.Controlled with record Backend_Name : S_Expressions.Atom_Refs.Immutable_Reference; Backend_Path : S_Expressions.Atom_Refs.Immutable_Reference; Parent_Path : S_Expressions.Atom_Refs.Immutable_Reference; Comments : Container_Refs.Reference; Post_Filter : S_Expressions.Atom_Refs.Immutable_Reference; Tags : Containers.Atom_Array_Refs.Immutable_Reference; Text_Filters : Containers.Atom_Array_Refs.Immutable_Reference; Default_Text_Filter : S_Expressions.Atom_Refs.Immutable_Reference; Flags : List_Flags.Set := (others => False); Parent : Web.Tags.Visible_Access; end record; overriding procedure Finalize (Object : in out Comment_List); type Comment_Inserter is new Sites.Updates.Site_Update with record Container : Container_Refs.Reference; Id : S_Expressions.Atom_Refs.Immutable_Reference; Tags : Containers.Atom_Array_Refs.Immutable_Reference; end record; overriding procedure Update (Self : in Comment_Inserter; Site : in out Sites.Site); package Id_Lists is new Ada.Containers.Doubly_Linked_Lists (S_Expressions.Atom_Refs.Immutable_Reference, S_Expressions.Atom_Refs."="); type Comment_Remover is new Sites.Updates.Site_Update with record Container : Container_Refs.Reference; Ids : Id_Lists.List; Tags : Containers.Atom_Array_Refs.Immutable_Reference; end record; overriding procedure Update (Self : in Comment_Remover; Site : in out Sites.Site); Empty_List : constant Comment_List := (Ada.Finalization.Controlled with Backend_Name => S_Expressions.Atom_Refs.Null_Immutable_Reference, Backend_Path => S_Expressions.Atom_Refs.Null_Immutable_Reference, Parent_Path => S_Expressions.Atom_Refs.Null_Immutable_Reference, Comments => Container_Refs.Null_Reference, Parent => null, Post_Filter => S_Expressions.Atom_Refs.Null_Immutable_Reference, Tags => Containers.Atom_Array_Refs.Null_Immutable_Reference, Text_Filters => Containers.Atom_Array_Refs.Null_Immutable_Reference, Default_Text_Filter => S_Expressions.Atom_Refs.Null_Immutable_Reference, Flags => (others => False)); end Natools.Web.Comments;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Comments provides an implementation of user-posted comments -- -- like is commonly found on blogs. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Printers; with Natools.Web.Sites; with Natools.Web.Tags; private with Ada.Calendar.Time_Zones; private with Ada.Containers.Doubly_Linked_Lists; private with Ada.Finalization; private with Natools.Constant_Indefinite_Ordered_Maps; private with Natools.References; private with Natools.Storage_Pools; private with Natools.Web.Containers; private with Natools.Web.Sites.Updates; package Natools.Web.Comments is type Comment_Ref is new Tags.Visible with private; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Comment_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- Render a comment type Comment_List is tagged private; function Is_Null (Object : in Comment_List) return Boolean; -- Return whether the list is usable (even if empty) procedure Load (Object : in out Comment_List; Builder : in out Sites.Site_Builder; Parent : in Tags.Visible_Access := null; Parent_Path : in S_Expressions.Atom_Refs.Immutable_Reference := S_Expressions.Atom_Refs.Null_Immutable_Reference); -- Load comment list from Builder back-end and register all comments procedure Render (Exchange : in out Sites.Exchange; Object : in Comment_List; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- Render a comment list procedure Respond (List : in out Comment_List; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom); -- Respond to a request for the comment list procedure Set (List : out Comment_List; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize List using data from Expression private package Comment_Atoms is type Enum is (Name, Mail, Link, Text, Class, Note, Title, Filter); type Set is array (Enum) of S_Expressions.Atom_Refs.Immutable_Reference; end Comment_Atoms; package Comment_Flags is type Enum is (Preprocessed, Ignored); type Set is array (Enum) of Boolean with Pack; end Comment_Flags; package List_Flags is type Enum is (Ignore_By_Default, Allow_Date_Override, Closed, Allow_Ignore); type Set is array (Enum) of Boolean with Pack; end List_Flags; type Comment_Data is record Date : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; Id : S_Expressions.Atom_Refs.Immutable_Reference; Atoms : Comment_Atoms.Set; Flags : Comment_Flags.Set := (others => False); Parent : Tags.Visible_Access; Rank : Positive; end record; procedure Preprocess (Comment : in out Comment_Data; List : in Comment_List; Site : in Sites.Site); procedure Preprocess (Comment : in out Comment_Data; List : in Comment_List; Builder : in Sites.Site_Builder); -- Preprocess comment field contents procedure Write (Comment : in Comment_Data; Output : in out S_Expressions.Printers.Printer'Class); -- Serialize a comment into the given S_Expression stream package Comment_Maps is new Natools.Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Comment_Data, S_Expressions."<"); procedure Set_Parent (Container : in out Comment_Maps.Updatable_Map; Parent : in Tags.Visible_Access); procedure Update_Ranks (Container : in out Comment_Maps.Updatable_Map); protected type Comment_Container is procedure Initialize (Data : in Comment_Maps.Unsafe_Maps.Map; Parent : in Tags.Visible_Access); procedure Insert (Data : in Comment_Data); procedure Ignore (Id : in S_Expressions.Atom; Ref : out S_Expressions.Atom_Refs.Immutable_Reference); procedure Orphan; function Find (Id : S_Expressions.Atom_Refs.Immutable_Reference) return Comment_Maps.Cursor; function First return Comment_Maps.Cursor; function Iterate return Comment_Maps.Map_Iterator_Interfaces.Reversible_Iterator'Class; function Length return Natural; private Map : Comment_Maps.Updatable_Map; Parent : Tags.Visible_Access; end Comment_Container; package Container_Refs is new References (Comment_Container, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); type Comment_Ref is new Tags.Visible with record Container : Container_Refs.Reference; Id : S_Expressions.Atom_Refs.Immutable_Reference; end record; type Comment_List is new Ada.Finalization.Controlled with record Backend_Name : S_Expressions.Atom_Refs.Immutable_Reference; Backend_Path : S_Expressions.Atom_Refs.Immutable_Reference; Parent_Path : S_Expressions.Atom_Refs.Immutable_Reference; Comments : Container_Refs.Reference; Post_Filter : S_Expressions.Atom_Refs.Immutable_Reference; Tags : Containers.Atom_Array_Refs.Immutable_Reference; Text_Filters : Containers.Atom_Array_Refs.Immutable_Reference; Default_Text_Filter : S_Expressions.Atom_Refs.Immutable_Reference; Flags : List_Flags.Set := (others => False); Parent : Web.Tags.Visible_Access; end record; overriding procedure Finalize (Object : in out Comment_List); function Is_Null (Object : in Comment_List) return Boolean is (Object.Backend_Name.Is_Empty or else Object.Backend_Path.Is_Empty); type Comment_Inserter is new Sites.Updates.Site_Update with record Container : Container_Refs.Reference; Id : S_Expressions.Atom_Refs.Immutable_Reference; Tags : Containers.Atom_Array_Refs.Immutable_Reference; end record; overriding procedure Update (Self : in Comment_Inserter; Site : in out Sites.Site); package Id_Lists is new Ada.Containers.Doubly_Linked_Lists (S_Expressions.Atom_Refs.Immutable_Reference, S_Expressions.Atom_Refs."="); type Comment_Remover is new Sites.Updates.Site_Update with record Container : Container_Refs.Reference; Ids : Id_Lists.List; Tags : Containers.Atom_Array_Refs.Immutable_Reference; end record; overriding procedure Update (Self : in Comment_Remover; Site : in out Sites.Site); Empty_List : constant Comment_List := (Ada.Finalization.Controlled with Backend_Name => S_Expressions.Atom_Refs.Null_Immutable_Reference, Backend_Path => S_Expressions.Atom_Refs.Null_Immutable_Reference, Parent_Path => S_Expressions.Atom_Refs.Null_Immutable_Reference, Comments => Container_Refs.Null_Reference, Parent => null, Post_Filter => S_Expressions.Atom_Refs.Null_Immutable_Reference, Tags => Containers.Atom_Array_Refs.Null_Immutable_Reference, Text_Filters => Containers.Atom_Array_Refs.Null_Immutable_Reference, Default_Text_Filter => S_Expressions.Atom_Refs.Null_Immutable_Reference, Flags => (others => False)); end Natools.Web.Comments;
add a primitive to test whether a comment list is usable
comments: add a primitive to test whether a comment list is usable
Ada
isc
faelys/natools-web,faelys/natools-web
30ea407b9e56444b310ed52a1c39ebf121f60b59
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Writer (Document : in out Html_Renderer; Writer : in Wiki.Writers.Html_Writer_Type_Access) is begin Document.Writer := Writer; end Set_Writer; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); case Level is when 1 => Document.Writer.Write_Wide_Element ("h1", Header); when 2 => Document.Writer.Write_Wide_Element ("h2", Header); when 3 => Document.Writer.Write_Wide_Element ("h3", Header); when 4 => Document.Writer.Write_Wide_Element ("h4", Header); when 5 => Document.Writer.Write_Wide_Element ("h5", Header); when 6 => Document.Writer.Write_Wide_Element ("h6", Header); when others => Document.Writer.Write_Wide_Element ("h3", Header); end case; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Html_Renderer) is begin -- Document.Writer.Write_Raw ("<br />"); Document.Writer.Write ("<br />"); end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Writer.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Writer.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Writer.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Writer.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Writer.Start_Element ("ol"); else Document.Writer.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Writer.End_Element ("p"); end if; if Document.Has_Item then Document.Writer.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Writer.End_Element ("ol"); else Document.Writer.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Writer.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Writer.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); Document.Writer.Start_Element ("hr"); Document.Writer.End_Element ("hr"); end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is Exists : Boolean; URI : Unbounded_Wide_Wide_String; begin Document.Open_Paragraph; Document.Writer.Start_Element ("a"); if Length (Title) > 0 then Document.Writer.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; Document.Links.Make_Page_Link (Link, URI, Exists); Document.Writer.Write_Wide_Attribute ("href", URI); Document.Writer.Write_Wide_Text (Name); Document.Writer.End_Element ("a"); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Writer.Start_Element ("img"); if Length (Alt) > 0 then Document.Writer.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Writer.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Writer.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Writer.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Writer.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Writer.End_Element ("img"); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Writer.Start_Element ("q"); if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Writer.Write_Wide_Attribute ("cite", Link); end if; Document.Writer.Write_Wide_Text (Quote); Document.Writer.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Open_Paragraph; for I in Format'Range loop if Format (I) then Document.Writer.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Document.Writer.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Document.Writer.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Writer.Write (Text); else Document.Writer.Start_Element ("pre"); Document.Writer.Write_Wide_Text (Text); Document.Writer.End_Element ("pre"); end if; end Add_Preformatted; overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes); begin Document.Html_Level := Document.Html_Level + 1; if Name = "p" then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; Document.Writer.Start_Element (Ada.Characters.Conversions.To_String (To_Wide_Wide_String (Name))); while Wiki.Attributes.Has_Element (Iter) loop Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; end Start_Element; overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String) is begin Document.Html_Level := Document.Html_Level - 1; if Name = "p" then Document.Has_Paragraph := False; Document.Need_Paragraph := True; end if; Document.Writer.End_Element (Ada.Characters.Conversions.To_String (To_Wide_Wide_String (Name))); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Writer (Document : in out Html_Renderer; Writer : in Wiki.Writers.Html_Writer_Type_Access) is begin Document.Writer := Writer; end Set_Writer; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); case Level is when 1 => Document.Writer.Write_Wide_Element ("h1", Header); when 2 => Document.Writer.Write_Wide_Element ("h2", Header); when 3 => Document.Writer.Write_Wide_Element ("h3", Header); when 4 => Document.Writer.Write_Wide_Element ("h4", Header); when 5 => Document.Writer.Write_Wide_Element ("h5", Header); when 6 => Document.Writer.Write_Wide_Element ("h6", Header); when others => Document.Writer.Write_Wide_Element ("h3", Header); end case; end Add_Header; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ overriding procedure Add_Line_Break (Document : in out Html_Renderer) is begin Document.Writer.Write ("<br />"); end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ overriding procedure Add_Paragraph (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Writer.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Writer.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Writer.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Writer.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Writer.Start_Element ("ol"); else Document.Writer.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Writer.End_Element ("p"); end if; if Document.Has_Item then Document.Writer.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Writer.End_Element ("ol"); else Document.Writer.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Writer.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Writer.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Add an horizontal rule (<hr>). -- ------------------------------ overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); Document.Writer.Start_Element ("hr"); Document.Writer.End_Element ("hr"); end Add_Horizontal_Rule; -- ------------------------------ -- Add a link. -- ------------------------------ overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is Exists : Boolean; URI : Unbounded_Wide_Wide_String; begin Document.Open_Paragraph; Document.Writer.Start_Element ("a"); if Length (Title) > 0 then Document.Writer.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; Document.Links.Make_Page_Link (Link, URI, Exists); Document.Writer.Write_Wide_Attribute ("href", URI); Document.Writer.Write_Wide_Text (Name); Document.Writer.End_Element ("a"); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ overriding procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Writer.Start_Element ("img"); if Length (Alt) > 0 then Document.Writer.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Writer.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Writer.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Writer.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Writer.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Writer.End_Element ("img"); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Writer.Start_Element ("q"); if Length (Language) > 0 then Document.Writer.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Writer.Write_Wide_Attribute ("cite", Link); end if; Document.Writer.Write_Wide_Text (Quote); Document.Writer.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map) is begin Document.Open_Paragraph; for I in Format'Range loop if Format (I) then Document.Writer.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Document.Writer.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Document.Writer.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Writer.Write (Text); else Document.Writer.Start_Element ("pre"); Document.Writer.Write_Wide_Text (Text); Document.Writer.End_Element ("pre"); end if; end Add_Preformatted; overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes); begin Document.Html_Level := Document.Html_Level + 1; if Name = "p" then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name))); while Wiki.Attributes.Has_Element (Iter) loop Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; end Start_Element; overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String) is begin Document.Html_Level := Document.Html_Level - 1; if Name = "p" then Document.Has_Paragraph := False; Document.Need_Paragraph := True; end if; Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name))); end End_Element; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0f9f433ec7f1c90ddafc99848916f44963304bea
src/util-serialize-tools.ads
src/util-serialize-tools.ads
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- 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.Beans.Objects.Maps; with Util.Serialize.IO.JSON; package Util.Serialize.Tools is -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Name : in String; Map : in Util.Beans.Objects.Maps.Map); -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map); -- Serialize the objects defined in the object map <b>Map</b> into an JSON stream. -- Returns the JSON string that contains a serialization of the object maps. function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String; -- Deserializes the XML content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map; end Util.Serialize.Tools;
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- 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 Util.Beans.Objects.Maps; with Util.Serialize.IO.JSON; package Util.Serialize.Tools is -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class; Name : in String; Map : in Util.Beans.Objects.Maps.Map); -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map); -- Serialize the objects defined in the object map <b>Map</b> into an JSON stream. -- Returns the JSON string that contains a serialization of the object maps. function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String; -- Deserializes the XML content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map; end Util.Serialize.Tools;
Change TO_JSON to accept class wide JSON Output_Stream
Change TO_JSON to accept class wide JSON Output_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
224fdf4a0233ffd6e77b217c2d7e73469af33f3e
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki.Helpers is LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki.Helpers is LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; end Wiki.Helpers;
Declare the Is_Url function
Declare the Is_Url function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3b3d2b576003bea1df510ecefa74ab0f2b011046
samples/pschema.adb
samples/pschema.adb
----------------------------------------------------------------------- -- pschema - Print the database schema -- 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 ADO; with ADO.Drivers.Mysql; with ADO.Schemas.Mysql; with ADO.Databases; with ADO.Sessions; with ADO.Sessions.Factory; with ADO.Schemas; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Command_Line; with Util.Log.Loggers; procedure Pschema is use ADO; use Ada; use Ada.Strings.Unbounded; use ADO.Schemas; Controller : ADO.Databases.DataSource; Factory : ADO.Sessions.Factory.Session_Factory; Verbose : Boolean; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; Schema : ADO.Schemas.Schema_Definition; Iter : Table_Cursor; begin ADO.Schemas.Mysql.Load_Schema (DB.Get_Connection, Schema); -- Dump the database schema using SQL create table forms. Iter := Get_Tables (Schema); while Has_Element (Iter) loop declare Table : constant Table_Definition := Element (Iter); CITer : Column_Cursor := Get_Columns (Table); begin Ada.Text_IO.Put_Line ("create table " & Get_Name (Table) & " ("); while Has_Element (CIter) loop declare Col : constant Column_Definition := Element (CIter); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Get_Name (Col)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Column_Type'Image (Get_Type (Col))); if not Is_Null (Col) then Ada.Text_IO.Put (" not null"); end if; Ada.Text_IO.Put_Line (","); end; Next (CIter); end loop; Ada.Text_IO.Put_Line (");"); end; Next (Iter); end loop; end; end Pschema;
----------------------------------------------------------------------- -- pschema - Print the database schema -- 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 ADO; with ADO.Schemas.Mysql; with ADO.Drivers; with ADO.Sessions; with ADO.Sessions.Factory; with ADO.Schemas; with Ada.Text_IO; with Util.Log.Loggers; procedure Pschema is use ADO; use Ada; use ADO.Schemas; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; Schema : ADO.Schemas.Schema_Definition; Iter : Table_Cursor; begin ADO.Schemas.Mysql.Load_Schema (DB.Get_Connection, Schema); -- Dump the database schema using SQL create table forms. Iter := Get_Tables (Schema); while Has_Element (Iter) loop declare Table : constant Table_Definition := Element (Iter); Table_Iter : Column_Cursor := Get_Columns (Table); begin Ada.Text_IO.Put_Line ("create table " & Get_Name (Table) & " ("); while Has_Element (Table_Iter) loop declare Col : constant Column_Definition := Element (Table_Iter); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Get_Name (Col)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Column_Type'Image (Get_Type (Col))); if not Is_Null (Col) then Ada.Text_IO.Put (" not null"); end if; Ada.Text_IO.Put_Line (","); end; Next (Table_Iter); end loop; Ada.Text_IO.Put_Line (");"); end; Next (Iter); end loop; end; end Pschema;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-ado
f357909c8b3191b75160b730179039aa73c85145
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; use type Interfaces.Unsigned_16; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
997f2fd2bd02c115960e21e450cbe49061947d4b
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.ads
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with ADO; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Public_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Private_Id : ADO.Identifier := ADO.NO_IDENTIFIER; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); -- Test creation of a wiki page content. procedure Test_Create_Wiki_Content (T : in out Test); procedure Test_Wiki_Page (T : in out Test); end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with ADO; package AWA.Wikis.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Wikis.Modules.Wiki_Module_Access; Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Public_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Private_Id : ADO.Identifier := ADO.NO_IDENTIFIER; end record; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test); -- Test creation of a wiki page. procedure Test_Create_Wiki_Page (T : in out Test); -- Test creation of a wiki page content. procedure Test_Create_Wiki_Content (T : in out Test); -- Test getting the wiki page as well as info, history pages. procedure Test_Wiki_Page (T : in out Test); end AWA.Wikis.Modules.Tests;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c42f6a8b6f399b0c2111d001571974ea84e11e04
src/gen-artifacts-query.adb
src/gen-artifacts-query.adb
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Operations; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the method definition in the table -- ------------------------------ procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Operation : Gen.Model.Operations.Operation_Definition_Access; begin Table.Add_Operation (Name, Operation); end Register_Operation; -- ------------------------------ -- Register all the operations defined in the table -- ------------------------------ procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Operation); begin Log.Debug ("Register operations from bean {0}", Table.Name); Iterate (Table, Node, "method"); end Register_Operations; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True); C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", False); C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); Register_Operations (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- 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 (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Operations; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the method definition in the table -- ------------------------------ procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Operation : Gen.Model.Operations.Operation_Definition_Access; begin Table.Add_Operation (Name, Operation); end Register_Operation; -- ------------------------------ -- Register all the operations defined in the table -- ------------------------------ procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Operation); begin Log.Debug ("Register operations from bean {0}", Table.Name); Iterate (Table, Node, "method"); end Register_Operations; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := Gen.Utils.Get_Attribute (Column, "update", True); C.Not_Null := Gen.Utils.Get_Attribute (Column, "not-null", True); C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); Register_Operations (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- 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 (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
Fix the default configuration for the not-null query column type
Fix the default configuration for the not-null query column type
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0f8246343f259ec42add6ab1f02539e7273abb88
matp/src/mat-targets.ads
matp/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Events.Probes; with MAT.Readers; with MAT.Readers.Streams; with MAT.Readers.Streams.Sockets; with MAT.Consoles; package MAT.Targets is pragma Preelaborate_Body; -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- 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); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Events.Probes; with MAT.Readers; with MAT.Readers.Streams; with MAT.Readers.Streams.Sockets; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Endian : MAT.Readers.Endian_Type := MAT.Readers.LITTLE_ENDIAN; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- 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); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
Add the Endian member in the Target_Process_Type
Add the Endian member in the Target_Process_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ee10412b102eb03f81aba4fd98e85b9471a980d8
src/ado-utils.adb
src/ado-utils.adb
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; end ADO.Utils;
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; -- ------------------------------ -- Compute the hash of the identifier. -- ------------------------------ function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is use Ada.Containers; begin if Key < 0 then return Hash_Type (-Key); else return Hash_Type (Key); end if; end Hash; end ADO.Utils;
Implement the Hash operation
Implement the Hash operation
Ada
apache-2.0
Letractively/ada-ado
429f1772233373137215977ff7c73e95b339e68c
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.Urls;
Remove Finish_Config which is not necessary
Remove Finish_Config which is not necessary
Ada
apache-2.0
Letractively/ada-security
a6ca25afa23d99d4fee6b5959d2a43b8acdc8145
src/wiki-parsers-common.ads
src/wiki-parsers-common.ads
----------------------------------------------------------------------- -- wiki-parsers-common -- Common operations with several wiki parsers -- Copyright (C) 2011 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Common is pragma Preelaborate; subtype Parser_Type is Parser; -- Check if this is a list item composed of '*' and '#' -- and terminated by a space. function Is_List (Text : in Wiki.Buffers.Buffer_Access; From : in Positive) return Boolean; procedure Skip_Spaces (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Append (Into : in out Wiki.Strings.BString; Text : in Wiki.Buffers.Buffer_Access; From : in Positive); procedure Parse_Token (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Escape_Char : in Wiki.Strings.WChar; Marker1 : in Wiki.Strings.WChar; Marker2 : in Wiki.Strings.WChar; Into : in out Wiki.Strings.BString); -- Parse a single text character and add it to the text buffer. procedure Parse_Text (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Count : in Positive := 1); procedure Parse_Paragraph (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Horizontal_Rule (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a preformatted header block. -- Example: -- /// -- ///html -- ///[Ada] -- {{{ -- ``` procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a wiki heading. The heading could start with '=' or '!'. -- The trailing equals are ignored. -- Example: -- ==== Level 4 Creole -- == Level 2 == MediaWiki -- !!! Level 3 Dotclear procedure Parse_Header (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in Positive; Marker : in Wiki.Strings.WChar); -- Parse a template with parameters. -- Example: -- {{Name|param|...}} MediaWiki -- {{Name|param=value|...}} MediaWiki -- <<Name param=value ...>> Creole -- [{Name param=value ...}] JSPWiki procedure Parse_Template (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Token : in Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Status : out Wiki.Html_Parser.Entity_State_Type; Entity : out Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a quote. -- Example: -- {{name}} -- {{name|language}} -- {{name|language|url}} -- ??citation?? procedure Parse_Quote (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); procedure Parse_Html_Element (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Start : in Boolean); procedure Parse_Html_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a link. -- Example: -- [name] -- [name|url] -- [name|url|language] -- [name|url|language|title] -- [[link]] -- [[link|name]] procedure Parse_Link (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_List (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a list definition that starts with ';': -- ;item 1 -- : definition 1 procedure Parse_Definition (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); end Wiki.Parsers.Common;
----------------------------------------------------------------------- -- wiki-parsers-common -- Common operations with several wiki parsers -- Copyright (C) 2011 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Common is pragma Preelaborate; subtype Parser_Type is Parser; -- Check if this is a list item composed of '*' and '#' -- and terminated by a space. function Is_List (Text : in Wiki.Buffers.Buffer_Access; From : in Positive) return Boolean; procedure Skip_Spaces (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Count : out Natural); procedure Append (Into : in out Wiki.Strings.BString; Text : in Wiki.Buffers.Buffer_Access; From : in Positive); procedure Parse_Token (Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Escape_Char : in Wiki.Strings.WChar; Marker1 : in Wiki.Strings.WChar; Marker2 : in Wiki.Strings.WChar; Into : in out Wiki.Strings.BString); -- Parse a single text character and add it to the text buffer. procedure Parse_Text (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Count : in Positive := 1); procedure Parse_Paragraph (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Horizontal_Rule (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); -- Parse a preformatted header block. -- Example: -- /// -- ///html -- ///[Ada] -- {{{ -- ``` procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar; Keep_Block : in Boolean := False); -- Parse a wiki heading. The heading could start with '=' or '!'. -- The trailing equals are ignored. -- Example: -- ==== Level 4 Creole -- == Level 2 == MediaWiki -- !!! Level 3 Dotclear procedure Parse_Header (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in Positive; Marker : in Wiki.Strings.WChar); -- Parse a template with parameters. -- Example: -- {{Name|param|...}} MediaWiki -- {{Name|param=value|...}} MediaWiki -- <<Name param=value ...>> Creole -- [{Name param=value ...}] JSPWiki procedure Parse_Template (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Token : in Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Status : out Wiki.Html_Parser.Entity_State_Type; Entity : out Wiki.Strings.WChar); procedure Parse_Entity (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a quote. -- Example: -- {{name}} -- {{name|language}} -- {{name|language|url}} -- ??citation?? procedure Parse_Quote (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Marker : in Wiki.Strings.WChar); procedure Parse_Html_Element (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Start : in Boolean); procedure Parse_Html_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a link. -- Example: -- [name] -- [name|url] -- [name|url|language] -- [name|url|language|title] -- [[link]] -- [[link|name]] procedure Parse_Link (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_List (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); -- Parse a list definition that starts with ';': -- ;item 1 -- : definition 1 procedure Parse_Definition (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); end Wiki.Parsers.Common;
Update Skip_Spaces to get a count of skipped spaces and update Parse_Preformatted to keep the block
Update Skip_Spaces to get a count of skipped spaces and update Parse_Preformatted to keep the block
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
29079928a4f5ec206013a58a41c515cb00115267
orka_glfw/src/orka-windows-glfw.adb
orka_glfw/src/orka-windows-glfw.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; with Orka.Logging; with GL.Context; with GL.Viewports; package body Orka.Windows.GLFW is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Messages.Log (Error, "GLFW " & Code'Image & ": " & Trim (Description)); end Print_Error; ----------------------------------------------------------------------------- overriding procedure Finalize (Object : in out GLFW_Context) is begin if Object.Flags.Debug then Messages.Log (Debug, "Shutting down GLFW"); end if; Standard.Glfw.Shutdown; end Finalize; overriding procedure Enable (Object : in out GLFW_Context; Subject : Contexts.Feature) is begin Contexts.Enable (Object.Features, Subject); end Enable; overriding function Enabled (Object : GLFW_Context; Subject : Contexts.Feature) return Boolean is (Contexts.Enabled (Object.Features, Subject)); overriding function Is_Current (Object : GLFW_Context) return Boolean is begin raise GL.Feature_Not_Supported_Exception; return True; end Is_Current; overriding procedure Make_Current (Object : GLFW_Context) is begin raise GL.Feature_Not_Supported_Exception; end Make_Current; overriding procedure Make_Current (Object : GLFW_Context; Window : in out Orka.Windows.Window'Class) is Reference : constant Standard.Glfw.Windows.Window_Reference := Standard.Glfw.Windows.Window (Window)'Access; begin Standard.Glfw.Windows.Context.Make_Current (Reference); end Make_Current; overriding procedure Make_Not_Current (Object : GLFW_Context) is begin Standard.Glfw.Windows.Context.Make_Current (null); -- TODO Make sure Object is current on calling task end Make_Not_Current; overriding function Version (Object : GLFW_Context) return Contexts.Context_Version is begin return (Major => GL.Context.Major_Version, Minor => GL.Context.Minor_Version); end Version; overriding function Flags (Object : GLFW_Context) return Contexts.Context_Flags is Flags : constant GL.Context.Context_Flags := GL.Context.Flags; Result : Contexts.Context_Flags; begin pragma Assert (Flags.Forward_Compatible); Result.Debug := Flags.Debug; Result.Robust := Flags.Robust_Access; Result.No_Error := Flags.No_Error; return Result; end Flags; overriding function Create_Context (Version : Contexts.Context_Version; Flags : Contexts.Context_Flags := (others => False)) return GLFW_Context is package Context_Hints renames Standard.Glfw.Windows.Context; begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Version.Major, Version.Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Client_API (Context_Hints.OpenGL); Standard.Glfw.Windows.Hints.Set_Profile (Context_Hints.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Flags.Debug); Standard.Glfw.Windows.Hints.Set_Robustness (if Flags.Robust then Context_Hints.Lose_Context_On_Reset else Context_Hints.No_Robustness); -- Standard.Glfw.Windows.Hints.Set_No_Error_Context (Flags.No_Error); return (Ada.Finalization.Limited_Controlled with Version => Version, Flags => Flags, Features => <>); end Create_Context; ----------------------------------------------------------------------------- overriding function Create_Window (Context : Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return GLFW_Window is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Windows.Hints.Set_Transparent_Framebuffer (Transparent); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), Title); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); Messages.Log (Debug, "Created GLFW window and GL context"); Messages.Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no")); Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no")); Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no")); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Standard.Glfw.Windows.Context.Make_Current (Reference); Messages.Log (Debug, " context:"); Messages.Log (Debug, " flags: " & Orka.Contexts.Image (Context.Flags)); Messages.Log (Debug, " version: " & GL.Context.Version_String); Messages.Log (Debug, " renderer: " & GL.Context.Renderer); GL.Viewports.Set_Clipping (GL.Viewports.Lower_Left, GL.Viewports.Zero_To_One); Result.Vertex_Array.Create; end; end return; end Create_Window; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Messages.Log (Debug, "Closing GLFW window"); Object.Vertex_Array.Delete; Standard.Glfw.Windows.Context.Make_Current (null); -- FIXME Requires context to be current => ask render task to release context Object.Destroy; Object.Finalized := True; end if; end Finalize; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointers.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is Prev_Position_X : constant GL.Types.Double := Object.Position_X; Prev_Position_Y : constant GL.Types.Double := Object.Position_Y; use type GL.Types.Double; begin Object.Scroll_X := 0.0; Object.Scroll_Y := 0.0; Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Keep track of Locked transitioned to True if Object.Input.Locked then Object.Got_Locked := Object.Got_Locked or not Object.Last_Locked; else Object.Got_Locked := False; end if; Object.Last_Locked := Object.Input.Locked; if Object.Got_Locked and then (Object.Position_X /= Prev_Position_X or Object.Position_Y /= Prev_Position_Y) then Object.Got_Locked := False; -- GLFW bug: Update position of mouse again to reset delta to 0.0 Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); end if; -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Enable_Vertical_Sync (Object : in out GLFW_Window; Enable : Boolean) is begin Standard.Glfw.Windows.Context.Set_Swap_Interval (if Enable then 1 else 0); end Enable_Vertical_Sync; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin -- Accumulate the offset because the callback can be called -- multiple times Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; with Orka.Logging; with GL.Context; with GL.Viewports; package body Orka.Windows.GLFW is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Messages.Log (Error, "GLFW " & Code'Image & ": " & Trim (Description)); end Print_Error; ----------------------------------------------------------------------------- overriding procedure Finalize (Object : in out GLFW_Context) is begin if Object.Flags.Debug then Messages.Log (Debug, "Shutting down GLFW"); end if; Standard.Glfw.Shutdown; end Finalize; overriding procedure Enable (Object : in out GLFW_Context; Subject : Contexts.Feature) is begin Contexts.Enable (Object.Features, Subject); end Enable; overriding function Enabled (Object : GLFW_Context; Subject : Contexts.Feature) return Boolean is (Contexts.Enabled (Object.Features, Subject)); overriding function Is_Current (Object : GLFW_Context) return Boolean is begin raise GL.Feature_Not_Supported_Exception; return True; end Is_Current; overriding procedure Make_Current (Object : GLFW_Context) is begin raise GL.Feature_Not_Supported_Exception; end Make_Current; overriding procedure Make_Current (Object : GLFW_Context; Window : in out Orka.Windows.Window'Class) is Reference : constant Standard.Glfw.Windows.Window_Reference := Standard.Glfw.Windows.Window (Window)'Access; begin Standard.Glfw.Windows.Context.Make_Current (Reference); end Make_Current; overriding procedure Make_Not_Current (Object : GLFW_Context) is begin Standard.Glfw.Windows.Context.Make_Current (null); -- TODO Make sure Object is current on calling task end Make_Not_Current; overriding function Version (Object : GLFW_Context) return Contexts.Context_Version is begin return (Major => GL.Context.Major_Version, Minor => GL.Context.Minor_Version); end Version; overriding function Flags (Object : GLFW_Context) return Contexts.Context_Flags is Flags : constant GL.Context.Context_Flags := GL.Context.Flags; Result : Contexts.Context_Flags; begin pragma Assert (Flags.Forward_Compatible); Result.Debug := Flags.Debug; Result.Robust := Flags.Robust_Access; Result.No_Error := Flags.No_Error; return Result; end Flags; overriding function Create_Context (Version : Contexts.Context_Version; Flags : Contexts.Context_Flags := (others => False)) return GLFW_Context is package Context_Hints renames Standard.Glfw.Windows.Context; begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Version.Major, Version.Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Client_API (Context_Hints.OpenGL); Standard.Glfw.Windows.Hints.Set_Profile (Context_Hints.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Flags.Debug); Standard.Glfw.Windows.Hints.Set_Robustness (if Flags.Robust then Context_Hints.Lose_Context_On_Reset else Context_Hints.No_Robustness); -- Standard.Glfw.Windows.Hints.Set_No_Error_Context (Flags.No_Error); return (Ada.Finalization.Limited_Controlled with Version => Version, Flags => Flags, Features => <>); end Create_Context; ----------------------------------------------------------------------------- overriding function Create_Window (Context : Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return GLFW_Window is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Windows.Hints.Set_Transparent_Framebuffer (Transparent); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), Title); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); Messages.Log (Debug, "Created GLFW window and GL context"); Messages.Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no")); Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no")); Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no")); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Standard.Glfw.Windows.Context.Make_Current (Reference); Messages.Log (Debug, " context:"); Messages.Log (Debug, " flags: " & Orka.Contexts.Image (Context.Flags)); Messages.Log (Debug, " version: " & GL.Context.Version_String); Messages.Log (Debug, " renderer: " & GL.Context.Renderer); GL.Viewports.Set_Clipping (GL.Viewports.Lower_Left, GL.Viewports.Zero_To_One); Result.Vertex_Array.Create; end; end return; end Create_Window; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Messages.Log (Debug, "Closing GLFW window"); Object.Vertex_Array.Delete; Standard.Glfw.Windows.Context.Make_Current (null); -- FIXME Requires context to be current => ask render task to release context Object.Destroy; Object.Finalized := True; end if; end Finalize; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointers.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is Prev_Position_X : constant GL.Types.Double := Object.Position_X; Prev_Position_Y : constant GL.Types.Double := Object.Position_Y; use type GL.Types.Double; begin Object.Scroll_X := 0.0; Object.Scroll_Y := 0.0; Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Keep track of Locked transitioned to True if Object.Input.Locked then Object.Got_Locked := Object.Got_Locked or not Object.Last_Locked; else Object.Got_Locked := False; end if; Object.Last_Locked := Object.Input.Locked; if Object.Got_Locked and then (Object.Position_X /= Prev_Position_X or Object.Position_Y /= Prev_Position_Y) then Object.Got_Locked := False; -- GLFW bug: Update position of mouse again to reset delta to 0.0 Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); end if; -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Enable_Vertical_Sync (Object : in out GLFW_Window; Enable : Boolean) is begin Standard.Glfw.Windows.Context.Set_Swap_Interval (if Enable then 1 else 0); end Enable_Vertical_Sync; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin -- Accumulate the offset because the callback can be called -- multiple times Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
Align text of window size in log messages with other text
glfw: Align text of window size in log messages with other text Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
523057bd7548e518e6b5c5a511aabeba8e4cc7cb
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "21"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "22"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump version for release
Bump version for release
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
3bc64167775f8553eb711eeade4efdcf102b3878
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "53"; copyright_years : constant String := "2015-2020"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc9"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.34"; previous_binutils : constant String := "2.33.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "54"; copyright_years : constant String := "2015-2020"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc9"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.34"; previous_binutils : constant String := "2.33.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump to next version (1.54)
Bump to next version (1.54)
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
221c3eb5dbed978e8e1310dfa06d561b2dc97767
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "02"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "03"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump to version 1.03 (term/dtrace fixes self-confirmed)
Bump to version 1.03 (term/dtrace fixes self-confirmed)
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
8935df4f1ef1c7eab25b44b7109c8c08747cd795
mat/src/mat-formats.ads
mat/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format the duration in seconds, milliseconds or microseconds. function Duration (Value : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; end MAT.Formats;
Define a new Event function to provide a simple form of event information
Define a new Event function to provide a simple form of event information
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0f19a15043431ae6a5ef9a8d5664be460fe96206
awa/regtests/awa-users-tests.adb
awa/regtests/awa-users-tests.adb
----------------------------------------------------------------------- -- 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 Util.Log; with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Get_Application.Dump_Routes (Util.Log.INFO_LEVEL); begin AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); -- It sometimes happen that Joe's password is changed by another test. -- Recover the password and make sure it is 'admin'. exception when others => T.Recover_Password ("[email protected]", "admin"); end; Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Run the recovery password process for the given user and change the password. -- ------------------------------ procedure Recover_Password (T : in out Test; Email : in String; Password : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", Password); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Recover_Password; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is begin T.Recover_Password ("[email protected]", "asf"); T.Recover_Password ("[email protected]", "admin"); end Test_Reset_Password_User; end AWA.Users.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Do_Get (Request, Reply, "/auth/validate.html?key=" & Key.Get_Access_Key, "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Get_Application.Dump_Routes (Util.Log.INFO_LEVEL); begin AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); -- It sometimes happen that Joe's password is changed by another test. -- Recover the password and make sure it is 'admin'. exception when others => T.Recover_Password ("[email protected]", "admin"); end; Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Run the recovery password process for the given user and change the password. -- ------------------------------ procedure Recover_Password (T : in out Test; Email : in String; Password : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", Password); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Recover_Password; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is begin T.Recover_Password ("[email protected]", "asf"); T.Recover_Password ("[email protected]", "admin"); end Test_Reset_Password_User; end AWA.Users.Tests;
Update the user registration test after the change of ASF.Tests.Do_Get operation
Update the user registration test after the change of ASF.Tests.Do_Get operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7212cd6c4010e784ef4262c3c8734f1590adb17a
src/asf-security-filters-oauth.ads
src/asf-security-filters-oauth.ads
----------------------------------------------------------------------- -- security-filters-oauth -- OAuth Security 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.Filters; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with Security.OAuth.Servers; use Security.OAuth; with Security.Policies; with Servlet.Security.Filters.OAuth; -- The <b>ASF.Security.Filters.OAuth</b> package provides a servlet filter that -- implements the RFC 6749 "Accessing Protected Resources" part: it extracts the OAuth -- access token, verifies the grant and the permission. The servlet filter implements -- the RFC 6750 "OAuth 2.0 Bearer Token Usage". -- package ASF.Security.Filters.OAuth renames Servlet.Security.Filters.OAuth;
----------------------------------------------------------------------- -- security-filters-oauth -- OAuth Security 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 Servlet.Security.Filters.OAuth; -- The <b>ASF.Security.Filters.OAuth</b> package provides a servlet filter that -- implements the RFC 6749 "Accessing Protected Resources" part: it extracts the OAuth -- access token, verifies the grant and the permission. The servlet filter implements -- the RFC 6750 "OAuth 2.0 Bearer Token Usage". -- package ASF.Security.Filters.OAuth renames Servlet.Security.Filters.OAuth;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
4b25802a7137b4b709619d50b4f1ede740362de2
src/sys/encoders/util-encoders-sha1.ads
src/sys/encoders/util-encoders-sha1.ads
----------------------------------------------------------------------- -- util-encoders-sha1 -- Compute SHA-1 hash -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.SHA1 is pragma Preelaborate; -- The SHA-1 binary hash (160-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. 19); -- The SHA-1 hash as hexadecimal string. subtype Digest is String (1 .. 40); subtype Base64_Digest is String (1 .. 28); -- ------------------------------ -- SHA1 Context -- ------------------------------ type Context is limited private; -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the SHA1 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA1 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA1 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); -- ------------------------------ -- SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; use Interfaces; type H_Array is array (0 .. 4) of Unsigned_32; type W_Array is array (0 .. 79) of Unsigned_32; -- Process the message block collected in the context. procedure Compute (Ctx : in out Context); type Context is new Ada.Finalization.Limited_Controlled with record W : W_Array; H : H_Array; Pos : Natural; Count : Unsigned_64; Pending : String (1 .. 3); Pending_Pos : Natural; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.SHA1;
----------------------------------------------------------------------- -- util-encoders-sha1 -- Compute SHA-1 hash -- Copyright (C) 2011, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.SHA1 is pragma Preelaborate; HASH_SIZE : constant := 20; -- The SHA-1 binary hash (160-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. HASH_SIZE - 1); -- The SHA-1 hash as hexadecimal string. subtype Digest is String (1 .. 2 * HASH_SIZE); subtype Base64_Digest is String (1 .. 28); -- ------------------------------ -- SHA1 Context -- ------------------------------ type Context is limited private; -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the SHA1 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA1 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA1 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); -- ------------------------------ -- SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; use Interfaces; type H_Array is array (0 .. 4) of Unsigned_32; type W_Array is array (0 .. 79) of Unsigned_32; -- Process the message block collected in the context. procedure Compute (Ctx : in out Context); type Context is new Ada.Finalization.Limited_Controlled with record W : W_Array; H : H_Array; Pos : Natural; Count : Unsigned_64; Pending : String (1 .. 3); Pending_Pos : Natural; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.SHA1;
Define HASH_SIZE and use it
Define HASH_SIZE and use it
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f1faa6d9b3fdb08d8cea10a985f0d3d89394d8b5
regtests/util-streams-tests.adb
regtests/util-streams-tests.adb
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- 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.Test_Caller; with Util.Encoders.AES; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Base64; with Util.Streams.AES; with Ada.IO_Exceptions; with Ada.Streams.Stream_IO; package body Util.Streams.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams"); generic Mode : in Util.Encoders.AES.AES_Mode; Label : in String; procedure Test_AES_Mode (T : in out Test); procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is Reader : aliased Util.Streams.Texts.Reader_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Key : Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); begin -- Print -> Cipher -> Decipher Decipher.Initialize (64 * 1024); Decipher.Set_Key (Key, Mode); Cipher.Initialize (Decipher'Access, 1024); Cipher.Set_Key (Key, Mode); Print.Initialize (Cipher'Access); for I in 1 .. Count loop Print.Write (Item); end loop; Print.Flush; Util.Tests.Assert_Equals (T, Item'Length * Count, Decipher.Get_Size, Label & ": decipher buffer has the wrong size mode"); -- Read content in Decipher Reader.Initialize (Decipher); for I in 1 .. Count loop declare L : String (Item'Range) := (others => ' '); begin for J in L'Range loop Reader.Read (L (J)); end loop; Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value"); exception when Ada.IO_Exceptions.Data_Error => Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)"); end; end loop; end Test_AES; procedure Test_AES_Mode (T : in out Test) is begin for I in 1 .. 128 loop Test_AES (T, "a", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "ab", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "abc", I, Mode, Label); end loop; end Test_AES_Mode; procedure Test_AES_ECB is new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB"); procedure Test_AES_CBC is new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC"); procedure Test_AES_PCBC is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC"); procedure Test_AES_CFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB"); procedure Test_AES_OFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB"); procedure Test_AES_CTR is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR"); procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Base64.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Access, Size => 5); Buffer.Initialize (Output => Stream'Access, Size => 1024); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read", Test_Base64_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)", Test_AES_ECB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)", Test_AES_CBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)", Test_AES_PCBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)", Test_AES_CFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)", Test_AES_OFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)", Test_AES_CTR'Access); end Add_Tests; end Util.Streams.Tests;
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- 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.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Base64; with Util.Streams.AES; with Ada.IO_Exceptions; with Ada.Streams.Stream_IO; package body Util.Streams.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams"); generic Mode : in Util.Encoders.AES.AES_Mode; Label : in String; procedure Test_AES_Mode (T : in out Test); procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is Reader : aliased Util.Streams.Texts.Reader_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Key : Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); begin -- Print -> Cipher -> Decipher Decipher.Initialize (64 * 1024); Decipher.Set_Key (Key, Mode); Cipher.Initialize (Decipher'Access, 1024); Cipher.Set_Key (Key, Mode); Print.Initialize (Cipher'Access); for I in 1 .. Count loop Print.Write (Item); end loop; Print.Flush; Util.Tests.Assert_Equals (T, Item'Length * Count, Decipher.Get_Size, Label & ": decipher buffer has the wrong size mode"); -- Read content in Decipher Reader.Initialize (Decipher); for I in 1 .. Count loop declare L : String (Item'Range) := (others => ' '); begin for J in L'Range loop Reader.Read (L (J)); end loop; Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value"); exception when Ada.IO_Exceptions.Data_Error => Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)"); end; end loop; end Test_AES; procedure Test_AES_Mode (T : in out Test) is begin for I in 1 .. 128 loop Test_AES (T, "a", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "ab", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "abc", I, Mode, Label); end loop; end Test_AES_Mode; procedure Test_AES_ECB is new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB"); procedure Test_AES_CBC is new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC"); procedure Test_AES_PCBC is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC"); procedure Test_AES_CFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB"); procedure Test_AES_OFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB"); procedure Test_AES_CTR is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR"); procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Base64.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Access, Size => 5); Buffer.Initialize (Output => Stream'Access, Size => 1024); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read", Test_Base64_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)", Test_AES_ECB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)", Test_AES_CBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)", Test_AES_PCBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)", Test_AES_CFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)", Test_AES_OFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)", Test_AES_CTR'Access); end Add_Tests; end Util.Streams.Tests;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b7cb14e506cc6ff33bb105dcd82c406d9a6c05b0
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "74"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.2.0"; previous_compiler : constant String := "7.1.0"; binutils_version : constant String := "2.29"; previous_binutils : constant String := "2.28"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "75"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.2.0"; previous_compiler : constant String := "7.1.0"; binutils_version : constant String := "2.29.1"; previous_binutils : constant String := "2.29"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Update ravenadm to use binutils 2.29.1 instead of 2.29
Update ravenadm to use binutils 2.29.1 instead of 2.29
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
f2bf5ef66e3f806681e1528b12807e42f75308dd
src/util-events.ads
src/util-events.ads
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Events is type Event is tagged private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; private type Event is tagged record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Events is type Event is tagged private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; type Event_Listener is limited interface; private type Event is tagged record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
Declare the Event_Listener interface
Declare the Event_Listener interface
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
c750fedaa7adfacb5bb1243ccea0860c0848caca
src/util-processes.ads
src/util-processes.ads
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; with Ada.Finalization; with Ada.Strings.Unbounded; package Util.Processes is Invalid_State : exception; Process_Error : exception; -- The optional process pipes: -- <dl> -- <dt>NONE</dt> -- <dd>the process will inherit the standard input, output and error.</dd> -- <dt>READ</dt> -- <dd>a pipe is created to read the process standard output.</dd> -- <dt>READ_ERROR</dt> -- <dd>a pipe is created to read the process standard error. The output and input are -- inherited.</dd> -- <dt>READ_ALL</dt> -- <dd>similar to READ the same pipe is used for the process standard error.</dd> -- <dt>WRITE</dt> -- <dd>a pipe is created to write on the process standard input.</dd> -- <dt>READ_WRITE</dt> -- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd> -- <dt>READ_WRITE_ALL</dt> -- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd> -- </dl> type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL); subtype String_Access is Ada.Strings.Unbounded.String_Access; type Argument_List is array (Positive range <>) of String_Access; type Process_Identifier is new Integer; -- ------------------------------ -- Process -- ------------------------------ type Process is limited private; -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Proc : in out Process; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Proc : in out Process; Path : in String); -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Proc : in out Process; Shell : in String); -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. procedure Append_Argument (Proc : in out Process; Arg : in String); -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List); procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE); -- Wait for the process to terminate. procedure Wait (Proc : in out Process); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Proc : in out Process; Signal : in Positive := 15); -- Get the process exit status. function Get_Exit_Status (Proc : in Process) return Integer; -- Get the process identifier. function Get_Pid (Proc : in Process) return Process_Identifier; -- Returns True if the process is running. function Is_Running (Proc : in Process) return Boolean; -- Get the process input stream allowing to write on the process standard input. function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access; -- Get the process output stream allowing to read the process standard output. function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; -- Get the process error stream allowing to read the process standard output. function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; private -- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the -- process identifier. On Windows, more information is necessary, including the process -- and thread handles. It's a little bit overkill to setup an interface for this but -- it looks cleaner than having specific system fields here. type System_Process is limited interface; type System_Process_Access is access all System_Process'Class; type Process is new Ada.Finalization.Limited_Controlled with record Pid : Process_Identifier := -1; Sys : System_Process_Access := null; Exit_Value : Integer := -1; Dir : Ada.Strings.Unbounded.Unbounded_String; In_File : Ada.Strings.Unbounded.Unbounded_String; Out_File : Ada.Strings.Unbounded.Unbounded_String; Err_File : Ada.Strings.Unbounded.Unbounded_String; Shell : Ada.Strings.Unbounded.Unbounded_String; Out_Append : Boolean := False; Err_Append : Boolean := False; Output : Util.Streams.Input_Stream_Access := null; Input : Util.Streams.Output_Stream_Access := null; Error : Util.Streams.Input_Stream_Access := null; end record; -- Initialize the process instance. overriding procedure Initialize (Proc : in out Process); -- Deletes the process instance. overriding procedure Finalize (Proc : in out Process); -- Wait for the process to exit. procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is abstract; -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is abstract; -- Spawn a new process. procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is abstract; -- Append the argument to the process argument list. procedure Append_Argument (Sys : in out System_Process; Arg : in String) is abstract; -- Set the process input, output and error streams to redirect and use specified files. procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean) is abstract; -- Deletes the storage held by the system process. procedure Finalize (Sys : in out System_Process) is abstract; end Util.Processes;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2012, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; with Util.Systems.Types; with Ada.Finalization; with Ada.Strings.Unbounded; package Util.Processes is Invalid_State : exception; Process_Error : exception; -- The optional process pipes: -- <dl> -- <dt>NONE</dt> -- <dd>the process will inherit the standard input, output and error.</dd> -- <dt>READ</dt> -- <dd>a pipe is created to read the process standard output.</dd> -- <dt>READ_ERROR</dt> -- <dd>a pipe is created to read the process standard error. The output and input are -- inherited.</dd> -- <dt>READ_ALL</dt> -- <dd>similar to READ the same pipe is used for the process standard error.</dd> -- <dt>WRITE</dt> -- <dd>a pipe is created to write on the process standard input.</dd> -- <dt>READ_WRITE</dt> -- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd> -- <dt>READ_WRITE_ALL</dt> -- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd> -- </dl> type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL); subtype String_Access is Ada.Strings.Unbounded.String_Access; subtype File_Type is Util.Systems.Types.File_Type; type Argument_List is array (Positive range <>) of String_Access; type Process_Identifier is new Integer; -- ------------------------------ -- Process -- ------------------------------ type Process is limited private; -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Proc : in out Process; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Proc : in out Process; Path : in String); -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Proc : in out Process; Shell : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Proc : in out Process; Fd : in File_Type); -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. procedure Append_Argument (Proc : in out Process; Arg : in String); -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List); procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE); -- Wait for the process to terminate. procedure Wait (Proc : in out Process); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Proc : in out Process; Signal : in Positive := 15); -- Get the process exit status. function Get_Exit_Status (Proc : in Process) return Integer; -- Get the process identifier. function Get_Pid (Proc : in Process) return Process_Identifier; -- Returns True if the process is running. function Is_Running (Proc : in Process) return Boolean; -- Get the process input stream allowing to write on the process standard input. function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access; -- Get the process output stream allowing to read the process standard output. function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; -- Get the process error stream allowing to read the process standard output. function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; private type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; -- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the -- process identifier. On Windows, more information is necessary, including the process -- and thread handles. It's a little bit overkill to setup an interface for this but -- it looks cleaner than having specific system fields here. type System_Process is limited interface; type System_Process_Access is access all System_Process'Class; type Process is new Ada.Finalization.Limited_Controlled with record Pid : Process_Identifier := -1; Sys : System_Process_Access := null; Exit_Value : Integer := -1; Dir : Ada.Strings.Unbounded.Unbounded_String; In_File : Ada.Strings.Unbounded.Unbounded_String; Out_File : Ada.Strings.Unbounded.Unbounded_String; Err_File : Ada.Strings.Unbounded.Unbounded_String; Shell : Ada.Strings.Unbounded.Unbounded_String; Out_Append : Boolean := False; Err_Append : Boolean := False; Output : Util.Streams.Input_Stream_Access := null; Input : Util.Streams.Output_Stream_Access := null; Error : Util.Streams.Input_Stream_Access := null; To_Close : File_Type_Array_Access; end record; -- Initialize the process instance. overriding procedure Initialize (Proc : in out Process); -- Deletes the process instance. overriding procedure Finalize (Proc : in out Process); -- Wait for the process to exit. procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is abstract; -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is abstract; -- Spawn a new process. procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is abstract; -- Append the argument to the process argument list. procedure Append_Argument (Sys : in out System_Process; Arg : in String) is abstract; -- Set the process input, output and error streams to redirect and use specified files. procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is abstract; -- Deletes the storage held by the system process. procedure Finalize (Sys : in out System_Process) is abstract; end Util.Processes;
Declare File_Type type and add Add_Close procedure Add To_Close parameter to the Set_Streams procedure
Declare File_Type type and add Add_Close procedure Add To_Close parameter to the Set_Streams procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fa236048ea5c058845813dcce4a44f1d5e741553
src/util-log.ads
src/util-log.ads
----------------------------------------------------------------------- -- util-log -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 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. ----------------------------------------------------------------------- -- = Logging = -- The `Util.Log` package and children provide a simple logging framework inspired -- from the Java Log4j library. It is intended to provide a subset of logging features -- available in other languages, be flexible, extensible, small and efficient. Having -- log messages in large applications is very helpful to understand, track and fix complex -- issues, some of them being related to configuration issues or interaction with other -- systems. The overhead of calling a log operation is negligeable when the log is disabled -- as it is in the order of 30ns and reasonable for a file appender has it is in the order -- of 5us. -- -- == Using the log framework == -- A bit of terminology: -- -- * A *logger* is the abstraction that provides operations to emit a message. The message -- is composed of a text, optional formatting parameters, a log level and a timestamp. -- * A *formatter* is the abstraction that takes the information about the log to format -- the final message. -- * An *appender* is the abstraction that writes the message either to a console, a file -- or some other final mechanism. -- -- == Logger Declaration == -- Similar to other logging framework such as Log4j and Log4cxx, it is necessary to have -- and instance of a logger to write a log message. The logger instance holds the configuration -- for the log to enable, disable and control the format and the appender that will receive -- the message. The logger instance is associated with a name that is used for the -- configuration. A good practice is to declare a `Log` instance in the package body or -- the package private part to make available the log instance to all the package operations. -- The instance is created by using the `Create` function. The name used for the configuration -- is free but using the full package name is helpful to control precisely the logs. -- -- with Util.Log.Loggers; -- package body X.Y is -- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y"); -- end X.Y; -- -- == Logger Messages == -- A log message is associated with a log level which is used by the logger instance to -- decide to emit or drop the log message. To keep the logging API simple and make it easily -- usable in the application, several operations are provided to write a message with different -- log level. -- -- A log message is a string that contains optional formatting markers that follow more or -- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`. -- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are -- replaced in the final message only when the message is enabled by the log configuration. -- The use of parameters allows to avoid formatting the log message when the log is not used. -- -- The example below shows several calls to emit a log message with different levels: -- -- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist"); -- Log.Warn ("The file {0} is empty", Path); -- Log.Info ("Opening file {0}", Path); -- Log.Debug ("Reading line {0}", Line); -- -- The logger also provides a special `Error` procedure that accepts an Ada exception -- occurence as parameter. The exception name and message are printed together with -- the error message. It is also possible to activate a complete traceback of the -- exception and report it in the error message. With this mechanism, an exception -- can be handled and reported easily: -- -- begin -- ... -- exception -- when E : others => -- Log.Error ("Something bad occurred", E, Trace => True); -- end; -- -- == Log Configuration == -- The log configuration uses property files close to the Apache Log4j and to the -- Apache Log4cxx configuration files. -- The configuration file contains several parts to configure the logging framework: -- -- * First, the *appender* configuration indicates the appender that exists and can receive -- a log message. -- * Second, a root configuration allows to control the default behavior of the logging -- framework. The root configuration controls the default log level as well as the -- appenders that can be used. -- * Last, a logger configuration is defined to control the logging level more precisely -- for each logger. -- -- Here is a simple log configuration that creates a file appender where log messages are -- written. The file appender is given the name `result` and is configured to write the -- messages in the file `my-log-file.log`. The file appender will use the `level-message` -- format for the layout of messages. Last is the configuration of the `X.Y` logger -- that will enable only messages starting from the `WARN` level. -- -- log4j.rootCategory=DEBUG,result -- log4j.appender.result=File -- log4j.appender.result.File=my-log-file.log -- log4j.appender.result.layout=level-message -- log4j.logger.X.Y=WARN -- -- package Util.Log is pragma Preelaborate; subtype Level_Type is Natural; FATAL_LEVEL : constant Level_Type := 0; ERROR_LEVEL : constant Level_Type := 5; WARN_LEVEL : constant Level_Type := 7; INFO_LEVEL : constant Level_Type := 10; DEBUG_LEVEL : constant Level_Type := 20; -- Get the log level name. function Get_Level_Name (Level : Level_Type) return String; -- Get the log level from the property value function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type; -- The <tt>Logging</tt> interface defines operations that can be implemented for a -- type to report errors or messages. type Logging is limited interface; procedure Error (Log : in out Logging; Message : in String) is abstract; end Util.Log;
----------------------------------------------------------------------- -- util-log -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 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. ----------------------------------------------------------------------- -- = Logging = -- The `Util.Log` package and children provide a simple logging framework inspired -- from the Java Log4j library. It is intended to provide a subset of logging features -- available in other languages, be flexible, extensible, small and efficient. Having -- log messages in large applications is very helpful to understand, track and fix complex -- issues, some of them being related to configuration issues or interaction with other -- systems. The overhead of calling a log operation is negligeable when the log is disabled -- as it is in the order of 30ns and reasonable for a file appender has it is in the order -- of 5us. -- -- == Using the log framework == -- A bit of terminology: -- -- * A *logger* is the abstraction that provides operations to emit a message. The message -- is composed of a text, optional formatting parameters, a log level and a timestamp. -- * A *formatter* is the abstraction that takes the information about the log to format -- the final message. -- * An *appender* is the abstraction that writes the message either to a console, a file -- or some other final mechanism. -- -- == Logger Declaration == -- Similar to other logging framework such as Java Log4j and Log4cxx, it is necessary to have -- and instance of a logger to write a log message. The logger instance holds the configuration -- for the log to enable, disable and control the format and the appender that will receive -- the message. The logger instance is associated with a name that is used for the -- configuration. A good practice is to declare a `Log` instance in the package body or -- the package private part to make available the log instance to all the package operations. -- The instance is created by using the `Create` function. The name used for the configuration -- is free but using the full package name is helpful to control precisely the logs. -- -- with Util.Log.Loggers; -- package body X.Y is -- Log : constant Util.Log.Loggers := Util.Log.Loggers.Create ("X.Y"); -- end X.Y; -- -- == Logger Messages == -- A log message is associated with a log level which is used by the logger instance to -- decide to emit or drop the log message. To keep the logging API simple and make it easily -- usable in the application, several operations are provided to write a message with different -- log level. -- -- A log message is a string that contains optional formatting markers that follow more or -- less the Java `MessageFormat` class. A parameter is represented by a number enclosed by `{}`. -- The first parameter is represented by `{0}`, the second by `{1}` and so on. Parameters are -- replaced in the final message only when the message is enabled by the log configuration. -- The use of parameters allows to avoid formatting the log message when the log is not used. -- -- The example below shows several calls to emit a log message with different levels: -- -- Log.Error ("Cannot open file {0}: {1}", Path, "File does not exist"); -- Log.Warn ("The file {0} is empty", Path); -- Log.Info ("Opening file {0}", Path); -- Log.Debug ("Reading line {0}", Line); -- -- The logger also provides a special `Error` procedure that accepts an Ada exception -- occurence as parameter. The exception name and message are printed together with -- the error message. It is also possible to activate a complete traceback of the -- exception and report it in the error message. With this mechanism, an exception -- can be handled and reported easily: -- -- begin -- ... -- exception -- when E : others => -- Log.Error ("Something bad occurred", E, Trace => True); -- end; -- -- == Log Configuration == -- The log configuration uses property files close to the Apache Log4j and to the -- Apache Log4cxx configuration files. -- The configuration file contains several parts to configure the logging framework: -- -- * First, the *appender* configuration indicates the appender that exists and can receive -- a log message. -- * Second, a root configuration allows to control the default behavior of the logging -- framework. The root configuration controls the default log level as well as the -- appenders that can be used. -- * Last, a logger configuration is defined to control the logging level more precisely -- for each logger. -- -- Here is a simple log configuration that creates a file appender where log messages are -- written. The file appender is given the name `result` and is configured to write the -- messages in the file `my-log-file.log`. The file appender will use the `level-message` -- format for the layout of messages. Last is the configuration of the `X.Y` logger -- that will enable only messages starting from the `WARN` level. -- -- log4j.rootCategory=DEBUG,result -- log4j.appender.result=File -- log4j.appender.result.File=my-log-file.log -- log4j.appender.result.layout=level-message -- log4j.logger.X.Y=WARN -- -- By default when the `layout` is not set or has an invalid value, the full message is -- reported and the generated log messages will look as follows: -- -- [2018-02-07 20:39:51] ERROR - X.Y - Cannot open file test.txt: File does not exist -- [2018-02-07 20:39:51] WARN - X.Y - The file test.txt is empty -- [2018-02-07 20:39:51] INFO - X.Y - Opening file test.txt -- [2018-02-07 20:39:51] DEBUG - X.Y - Reading line ...... -- -- When the `layout` configuration is set to `data-level-message`, the message is printed -- with the date and message level. -- -- [2018-02-07 20:39:51] ERROR: Cannot open file test.txt: File does not exist -- [2018-02-07 20:39:51] WARN : The file test.txt is empty -- [2018-02-07 20:39:51] INFO : X.Y - Opening file test.txt -- [2018-02-07 20:39:51] DEBUG: X.Y - Reading line ...... -- -- When the `layout` configuration is set to `level-message`, only the message and its -- level are reported. -- -- ERROR: Cannot open file test.txt: File does not exist -- WARN : The file test.txt is empty -- INFO : X.Y - Opening file test.txt -- DEBUG: X.Y - Reading line ...... -- -- The last possible configuration for `layout` is `message` which only prints the message. -- -- Cannot open file test.txt: File does not exist -- The file test.txt is empty -- Opening file test.txt -- Reading line ...... -- package Util.Log is pragma Preelaborate; subtype Level_Type is Natural; FATAL_LEVEL : constant Level_Type := 0; ERROR_LEVEL : constant Level_Type := 5; WARN_LEVEL : constant Level_Type := 7; INFO_LEVEL : constant Level_Type := 10; DEBUG_LEVEL : constant Level_Type := 20; -- Get the log level name. function Get_Level_Name (Level : Level_Type) return String; -- Get the log level from the property value function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type; -- The <tt>Logging</tt> interface defines operations that can be implemented for a -- type to report errors or messages. type Logging is limited interface; procedure Error (Log : in out Logging; Message : in String) is abstract; end Util.Log;
Add more documentation about the layout formats
Add more documentation about the layout formats
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util