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
fad7b5584d7e09715ca3615af973269f0cc1edf8
src/dynamo.adb
src/dynamo.adb
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Traceback.Symbolic; with Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Directories; with Ada.Command_Line; with Util.Log.Loggers; with Gen.Generator; with Gen.Commands; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Directories; use Ada.Command_Line; use Gen.Commands; procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False); Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; Status : Exit_Status := Success; -- ------------------------------ -- Verify and set the configuration path -- ------------------------------ procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False) is Log_Path : constant String := Ada.Directories.Compose (Path, "log4j.properties"); begin -- Ignore if the config directory was already set. if Length (Config_Dir) > 0 then return; end if; -- Check that we can read some configuration file. if not Ada.Directories.Exists (Log_Path) then if not Silent then Ada.Text_IO.Put_Line ("Invalid config directory: " & Path); Status := Failure; end if; return; end if; -- Configure the logs Util.Log.Loggers.Initialize (Log_Path); Config_Dir := To_Unbounded_String (Path); end Set_Config_Directory; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Set_Config_Directory (Parameter); when others => null; end case; end loop; if Length (Config_Dir) = 0 then declare Name : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Name); begin Set_Config_Directory (Compose (Containing_Directory (Path), "config"), True); Set_Config_Directory (Gen.CONFIG_DIR, True); end; end if; if Status /= Success then Ada.Command_Line.Set_Exit_Status (Status); return; end if; declare Cmd_Name : constant String := Get_Argument; Cmd : constant Gen.Commands.Command_Access := Gen.Commands.Find_Command (Cmd_Name); Generator : Gen.Generator.Handler; begin -- Check that the command exists. if Cmd = null then if Cmd_Name'Length > 0 then Ada.Text_IO.Put_Line ("Invalid command: '" & Cmd_Name & "'"); else Ada.Text_IO.Put_Line (Gen.RELEASE); Ada.Text_IO.Put ("Type '"); Ada.Text_IO.Put (Ada.Command_Line.Command_Name); Ada.Text_IO.Put_Line (" help' for usage."); end if; Set_Exit_Status (Failure); return; end if; if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); Cmd.Execute (Generator); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Ada.Text_IO.Put_Line ("Use the 'help' command."); Ada.Command_Line.Set_Exit_Status (2); when E : Gen.Generator.Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : Sax.Readers.XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end Dynamo;
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Traceback.Symbolic; with Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Directories; with Ada.Command_Line; with Util.Files; with Util.Log.Loggers; with Gen.Generator; with Gen.Commands; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Directories; use Ada.Command_Line; use Gen.Commands; procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False); Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; Status : Exit_Status := Success; -- ------------------------------ -- Verify and set the configuration path -- ------------------------------ procedure Set_Config_Directory (Path : in String; Silent : in Boolean := False) is Log_Path : constant String := Ada.Directories.Compose (Path, "log4j.properties"); begin -- Ignore if the config directory was already set. if Length (Config_Dir) > 0 then return; end if; -- Check that we can read some configuration file. if not Ada.Directories.Exists (Log_Path) then if not Silent then Ada.Text_IO.Put_Line ("Invalid config directory: " & Path); Status := Failure; end if; return; end if; -- Configure the logs Util.Log.Loggers.Initialize (Log_Path); Config_Dir := To_Unbounded_String (Path); end Set_Config_Directory; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Set_Config_Directory (Parameter); when others => null; end case; end loop; if Length (Config_Dir) = 0 then declare Name : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Name); Dir : constant String := Containing_Directory (Path); begin Set_Config_Directory (Compose (Dir, "config"), True); Set_Config_Directory (Util.Files.Compose (Dir, "share/dynamo/base"), True); Set_Config_Directory (Gen.CONFIG_DIR, True); end; end if; if Status /= Success then Ada.Command_Line.Set_Exit_Status (Status); return; end if; declare Cmd_Name : constant String := Get_Argument; Cmd : constant Gen.Commands.Command_Access := Gen.Commands.Find_Command (Cmd_Name); Generator : Gen.Generator.Handler; begin -- Check that the command exists. if Cmd = null then if Cmd_Name'Length > 0 then Ada.Text_IO.Put_Line ("Invalid command: '" & Cmd_Name & "'"); else Ada.Text_IO.Put_Line (Gen.RELEASE); Ada.Text_IO.Put ("Type '"); Ada.Text_IO.Put (Ada.Command_Line.Command_Name); Ada.Text_IO.Put_Line (" help' for usage."); end if; Set_Exit_Status (Failure); return; end if; if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); Cmd.Execute (Generator); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Ada.Text_IO.Put_Line ("Use the 'help' command."); Ada.Command_Line.Set_Exit_Status (2); when E : Gen.Generator.Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : Sax.Readers.XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (1); when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end Dynamo;
Fix config directory search path - look for the dynamo configuration files in ../share/dynamo/base (relative to the dynamo executable path)
Fix config directory search path - look for the dynamo configuration files in ../share/dynamo/base (relative to the dynamo executable path)
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
5812008002b0b526155c85f6ac27ae92ae390e1f
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
----------------------------------------------------------------------- -- awa-storages-stores-files -- File system store -- 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.Streams; with Ada.Directories; with Interfaces; with Util.Files; with Util.Log.Loggers; with Util.Encoders; with Util.Encoders.Base64; package body AWA.Storages.Stores.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files"); -- ------------------------------ -- Create a file storage service and use the <tt>Root</tt> directory to store the files. -- ------------------------------ function Create_File_Store (Root : in String) return Store_Access is Result : constant File_Store_Access := new File_Store '(Len => Root'Length, Root => Root); begin return Result.all'Access; end Create_File_Store; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Store : in AWA.Storages.Models.Storage_Ref'Class) return String is begin return Storage.Get_Path (Store.Get_Workspace.Get_Id, Store.Get_Id); end Get_Path; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Workspace_Id : in ADO.Identifier; File_Id : in ADO.Identifier) return String is use Interfaces; use type Ada.Streams.Stream_Element_Offset; T : Util.Encoders.Base64.Encoder; Buffer : Ada.Streams.Stream_Element_Array (1 .. 10); R : Ada.Streams.Stream_Element_Array (1 .. 32); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Pos : Positive := 1; Res : String (1 .. 16 + 5); begin Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last); Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (File_Id), Last); T.Transform (Data => Buffer (1 .. Last), Into => R, Last => Last, Encoded => Encoded); for I in 1 .. Last loop Res (Pos) := Character'Val (R (I)); Pos := Pos + 1; if (I mod 2) = 0 and I /= Last then Res (Pos) := '/'; Pos := Pos + 1; end if; end loop; return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1)); end Get_Path; -- ------------------------------ -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. -- ------------------------------ procedure Save (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (Into); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage save {0} to {1}", Path, Store); Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Path, Target_Name => Store, Form => "all"); end Save; procedure Load (Storage : in File_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out Storage_File) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Load; -- ------------------------------ -- Create a storage -- ------------------------------ procedure Create (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is pragma Unreferenced (Storage); Store : constant String := Storage.Get_Path (From); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage create {0}", Store); Ada.Directories.Create_Path (Dir); Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Create; -- ------------------------------ -- Delete the content associate with the storage represented by `From`. -- ------------------------------ procedure Delete (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin if Ada.Directories.Exists (Store) then Log.Info ("Storage delete {0}", Store); Ada.Directories.Delete_File (Store); end if; end Delete; end AWA.Storages.Stores.Files;
----------------------------------------------------------------------- -- awa-storages-stores-files -- File system store -- 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.Streams; with Ada.Directories; with Interfaces; with Util.Files; with Util.Log.Loggers; with Util.Encoders; with Util.Encoders.Base64; package body AWA.Storages.Stores.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files"); -- ------------------------------ -- Create a file storage service and use the <tt>Root</tt> directory to store the files. -- ------------------------------ function Create_File_Store (Root : in String) return Store_Access is Result : constant File_Store_Access := new File_Store '(Len => Root'Length, Root => Root); begin return Result.all'Access; end Create_File_Store; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Store : in AWA.Storages.Models.Storage_Ref'Class) return String is begin return Storage.Get_Path (Store.Get_Workspace.Get_Id, Store.Get_Id); end Get_Path; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Workspace_Id : in ADO.Identifier; File_Id : in ADO.Identifier) return String is use Interfaces; use type Ada.Streams.Stream_Element_Offset; T : Util.Encoders.Base64.Encoder; Buffer : Ada.Streams.Stream_Element_Array (1 .. 10); R : Ada.Streams.Stream_Element_Array (1 .. 32); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Pos : Positive := 1; Res : String (1 .. 16 + 5); begin Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last); Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (File_Id), Last); T.Transform (Data => Buffer (1 .. Last), Into => R, Last => Last, Encoded => Encoded); for I in 1 .. Last loop Res (Pos) := Character'Val (R (I)); Pos := Pos + 1; if (I mod 2) = 0 and I /= Last then Res (Pos) := '/'; Pos := Pos + 1; end if; end loop; return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1)); end Get_Path; -- ------------------------------ -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. -- ------------------------------ procedure Save (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (Into); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage save {0} to {1}", Path, Store); Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Path, Target_Name => Store, Form => "all"); end Save; procedure Load (Storage : in File_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out Storage_File) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Load; -- ------------------------------ -- Create a storage -- ------------------------------ procedure Create (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage create {0}", Store); Ada.Directories.Create_Path (Dir); Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Create; -- ------------------------------ -- Delete the content associate with the storage represented by `From`. -- ------------------------------ procedure Delete (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin if Ada.Directories.Exists (Store) then Log.Info ("Storage delete {0}", Store); Ada.Directories.Delete_File (Store); end if; end Delete; end AWA.Storages.Stores.Files;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
62ca30fa7eaa199b4ff688650ccadf5477c2adbc
src/util-beans-objects-hash.adb
src/util-beans-objects-hash.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Hash -- Hash on an object -- 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.Strings.Hash; with Ada.Strings.Wide_Wide_Hash; with Ada.Unchecked_Conversion; with Interfaces; with Util.Beans.Basic; function Util.Beans.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Interfaces; use Util.Beans.Basic; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Duration is Unsigned_32_Array (1 .. Duration'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for duration. function To_U32_For_Duration is new Ada.Unchecked_Conversion (Source => Duration, Target => U32_For_Duration); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); begin case Key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.String_Proxy = null then return 0; else return Hash (Key.V.String_Proxy.Value); end if; when TYPE_TIME => declare U32 : constant U32_For_Duration := To_U32_For_Duration (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Wide_Proxy = null then return 0; else return Wide_Wide_Hash (Key.V.Wide_Proxy.Value); end if; when TYPE_BEAN => if Key.V.Proxy = null or else Bean_Proxy (Key.V.Proxy.all).Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Bean_Proxy (Key.V.Proxy.all).Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; end case; end Util.Beans.Objects.Hash;
----------------------------------------------------------------------- -- Util.Beans.Objects.Hash -- Hash on an object -- Copyright (C) 2010, 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.Strings.Hash; with Ada.Strings.Wide_Wide_Hash; with Ada.Unchecked_Conversion; with Interfaces; with Util.Beans.Basic; function Util.Beans.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Interfaces; use Util.Beans.Basic; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Duration is Unsigned_32_Array (1 .. Duration'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for duration. function To_U32_For_Duration is new Ada.Unchecked_Conversion (Source => Duration, Target => U32_For_Duration); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); begin case Key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.String_Proxy = null then return 0; else return Hash (Key.V.String_Proxy.Value); end if; when TYPE_TIME => declare U32 : constant U32_For_Duration := To_U32_For_Duration (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Wide_Proxy = null then return 0; else return Wide_Wide_Hash (Key.V.Wide_Proxy.Value); end if; when TYPE_BEAN => if Key.V.Proxy = null or else Bean_Proxy (Key.V.Proxy.all).Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Bean_Proxy (Key.V.Proxy.all).Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_ARRAY => declare Result : Unsigned_32 := 0; begin for Object of Key.V.Array_Proxy.Values loop Result := Result xor Unsigned_32 (Hash (Object)); end loop; return Hash_Type (Result); end; end case; end Util.Beans.Objects.Hash;
Update the Hash function to compute the hash for the array type
Update the Hash function to compute the hash for the array type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3f89a6de59fa9b2ceba9c76c35167fde2590035f
src/util-properties-bundles.adb
src/util-properties-bundles.adb
----------------------------------------------------------------------- -- util-properties-bundles -- Generic name/value property management -- Copyright (C) 2001 - 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 Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl = null then Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; end if; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Util.Concurrent.Counters.Increment (Bundle.Impl.Count); Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name); begin if Util.Beans.Objects.Is_Null (Result) then declare Iter : Cursor := From.List.First; begin while Has_Element (Iter) loop Result := Element (Iter).all.Get_Value (Name); exit when not Util.Beans.Objects.Is_Null (Result); Iter := Next (Iter); end loop; end; end if; return Result; end Get_Value; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in String) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in String) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
----------------------------------------------------------------------- -- util-properties-bundles -- Generic name/value property management -- Copyright (C) 2001 - 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 Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl = null then Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; end if; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Util.Concurrent.Counters.Increment (Bundle.Impl.Count); Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Info ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object is Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name); begin if Util.Beans.Objects.Is_Null (Result) then declare Iter : Cursor := From.List.First; begin while Has_Element (Iter) loop Result := Element (Iter).all.Get_Value (Name); exit when not Util.Beans.Objects.Is_Null (Result); Iter := Next (Iter); end loop; end; end if; return Result; end Get_Value; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in String) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in String) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
Change a Log.Debug into a Log.Info to better track resource bundle loading
Change a Log.Debug into a Log.Info to better track resource bundle loading
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e572b15f62ffe5f0b312cf71c414a81b6b2ec2c5
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Maps; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is use type Ada.Strings.Maps.Character_Set; function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); Marker : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" .,;:!?)") or Ada.Strings.Maps.To_Set (ASCII.HT) or Ada.Strings.Maps.To_Set (ASCII.VT) or Ada.Strings.Maps.To_Set (ASCII.CR) or Ada.Strings.Maps.To_Set (ASCII.LF); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Start : Natural := Text'First; Last : Natural := Text'Last; Link : Util.Strings.Maps.Cursor; Pos : Natural; begin Log.Debug ("Auto link |{0}|", Text); loop -- Emit spaces at beginning of line or words. while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop Ada.Text_IO.Put (File, Text (Start)); Start := Start + 1; end loop; exit when Start > Text'Last; -- Find a possible link. Link := Formatter.Links.Find (Text (Start .. Last)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Start .. Last)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Start := Last + 1; Last := Text'Last; else Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker, Going => Ada.Strings.Backward); if Pos = 0 then Ada.Text_IO.Put (File, Text (Start .. Last)); Start := Last + 1; Last := Text'Last; else Last := Pos - 1; -- Skip spaces at end of words for the search. while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop Last := Last - 1; end loop; end if; end if; end loop; end Write_Text_Auto_Links; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; Link : Util.Strings.Maps.Cursor; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last)); return; end if; Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Link := Formatter.Links.Find (Text (Pos .. Last_Pos)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, "]"); else Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos)); end if; end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => if Formatter.Mode /= L_START_CODE then Formatter.Mode := L_TEXT; end if; Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Maps; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is use type Ada.Text_IO.Positive_Count; use type Ada.Strings.Maps.Character_Set; function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); Marker : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (" .,;:!?)") or Ada.Strings.Maps.To_Set (ASCII.HT) or Ada.Strings.Maps.To_Set (ASCII.VT) or Ada.Strings.Maps.To_Set (ASCII.CR) or Ada.Strings.Maps.To_Set (ASCII.LF); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; procedure Write_Text_Auto_Links (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Start : Natural := Text'First; Last : Natural := Text'Last; Link : Util.Strings.Maps.Cursor; Pos : Natural; begin Log.Debug ("Auto link |{0}|", Text); loop -- Emit spaces at beginning of line or words. while Start <= Text'Last and then Ada.Strings.Maps.Is_In (Text (Start), Marker) loop Ada.Text_IO.Put (File, Text (Start)); Start := Start + 1; end loop; exit when Start > Text'Last; -- Find a possible link. Link := Formatter.Links.Find (Text (Start .. Last)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Start .. Last)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Start := Last + 1; Last := Text'Last; else Pos := Ada.Strings.Fixed.Index (Text (Start .. Last), Marker, Going => Ada.Strings.Backward); if Pos = 0 then Ada.Text_IO.Put (File, Text (Start .. Last)); Start := Last + 1; Last := Text'Last; else Last := Pos - 1; -- Skip spaces at end of words for the search. while Last > Start and then Ada.Strings.Maps.Is_In (Text (Last), Marker) loop Last := Last - 1; end loop; end if; end if; end loop; end Write_Text_Auto_Links; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; Link : Util.Strings.Maps.Cursor; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Formatter.Write_Text_Auto_Links (File, Text (Start .. Text'Last)); return; end if; Formatter.Write_Text_Auto_Links (File, Text (Start .. Pos - 1)); if Pos - 1 >= Text'First and then (Text (Pos - 1) = '\' or Text (Pos - 1) = '`') then Ada.Text_IO.Put (File, "["); Start := Pos + 1; -- Parse a markdown link format. elsif Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Log.Info ("Check link {0}", Text (Pos .. Last_Pos)); Link := Formatter.Links.Find (Text (Pos .. Last_Pos)); if Util.Strings.Maps.Has_Element (Link) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Util.Strings.Maps.Element (Link)); Ada.Text_IO.Put (File, ")"); Last_Pos := Last_Pos + 1; else Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos)); end if; end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); else case Formatter.Mode is when L_TEXT => Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); when L_LIST | L_LIST_ITEM => Formatter.Write_Text (File, Line); when others => Ada.Text_IO.Put_Line (File, Line); end case; end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); -- Ada.Text_IO.Put (File, Line.Content); Formatter.Write_Line (File, Line.Content); if Ada.Text_IO.Col (File) /= 1 then Formatter.Need_Newline := True; end if; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Formatter.Write_Line (File, Line.Content); -- Ada.Text_IO.Put (File, Line.Content); -- Formatter.Need_Newline := True; if Ada.Text_IO.Col (File) /= 1 then Formatter.Need_Newline := True; end if; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => if Formatter.Mode /= L_START_CODE then Formatter.Mode := L_TEXT; end if; Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Fix handling of auto-links in markdown bullet lists
Fix handling of auto-links in markdown bullet lists
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d8df06c57337aa3059ccd30d6672efc2d8fb49e2
awa/plugins/awa-questions/src/awa-questions-modules.ads
awa/plugins/awa-questions/src/awa-questions-modules.ads
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with AWA.Modules; with AWA.Questions.Services; package AWA.Questions.Modules is -- The name under which the module is registered. NAME : constant String := "questions"; -- ------------------------------ -- Module questions -- ------------------------------ type Question_Module is new AWA.Modules.Module with private; type Question_Module_Access is access all Question_Module'Class; -- Initialize the questions module. overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the question manager. function Get_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access; -- Create a question manager. This operation can be overridden to provide another -- question service implementation. function Create_Question_Manager (Plugin : in Question_Module) return Services.Question_Service_Access; -- Get the questions module. function Get_Question_Module return Question_Module_Access; -- Get the question manager instance associated with the current application. function Get_Question_Manager return Services.Question_Service_Access; private type Question_Module is new AWA.Modules.Module with record Manager : AWA.Questions.Services.Question_Service_Access; end record; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Questions.Models; package AWA.Questions.Modules is -- The name under which the module is registered. NAME : constant String := "questions"; -- Define the permissions. package ACL_Create_Questions is new Security.Permissions.Definition ("question-create"); package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete"); package ACL_Update_Questions is new Security.Permissions.Definition ("question-update"); package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create"); package ACL_Delete_Answer is new Security.Permissions.Definition ("answer-delete"); -- The maximum length for a short description. SHORT_DESCRIPTION_LENGTH : constant Positive := 200; -- ------------------------------ -- Module questions -- ------------------------------ type Question_Module is new AWA.Modules.Module with private; type Question_Module_Access is access all Question_Module'Class; -- Initialize the questions module. overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the questions module. function Get_Question_Module return Question_Module_Access; -- Create or save the question. procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Delete the question. procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class); -- Load the question. procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier); -- Create or save the answer. procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Delete the answer. procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class); -- Load the answer. procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier); private type Question_Module is new AWA.Modules.Module with null record; end AWA.Questions.Modules;
Move the question services in the question module (simplify the implementation)
Move the question services in the question module (simplify the implementation)
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
cfd4cac9d10ed8a9f678a5435ec936c38ebdc33e
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); -- Get the property manager represented by the item value. -- Raise the Conversion_Error exception if the value is not a property manager. function To_Manager (Item : in Value) return Manager; private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Declare the To_Manager function to convert a value to a property manager
Declare the To_Manager function to convert a value to a property manager
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
644ade96c1b1497b6f6fbc3861d3962630e48a42
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 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 Ada.Strings.Unbounded; with Ada.Finalization; with ADO; -- = Storages Module = -- The `storages` module provides a set of storage services allowing -- an application to store data files, documents, images in a persistent area. -- The persistent store can be on a file system, in the database or provided -- by a remote service such as Amazon Simple Storage Service. -- -- @include awa-storages-modules.ads -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. -- The data itself can be physically stored in a file system (`FILE` mode), -- in the database (`DATABASE` mode) or on a remote server (`URL` mode). -- To put a file in the storage space, first create the storage object -- instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses -- this information to save the data in a file, in the database or in -- a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the -- storage service. -- It will read the file and put in in the corresponding persistent store -- (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated -- a unique identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been -- designed to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able -- to read the file. If the storage mode of the data is `FILE`, the path -- of the file on the storage file system is used. For other storage modes, -- the file is saved in a temporary file. In that case the `Store_Local` -- database table is used to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream -- connection is the most efficient mechanism. -- -- == Local file == -- To access the data by using a local file, we must define a local storage -- reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading -- locally we also indicate whether the file will be read or written. A file -- that is in `READ` mode can be shared by several tasks or processes. -- A file that is in `WRITE` mode will have a specific copy for the caller. -- An optional expiration parameter indicate when the local file representation -- can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include-bean storages.xml -- @include-bean storage-list.xml -- @include-bean folder-queries.xml -- @include-bean storage-queries.xml -- -- @include awa-storages-servlets.ads -- -- == Queries == -- @include-query storage-list.xml -- @include-query folder-queries.xml -- @include-query storage-queries.xml -- -- == Data model == -- [images/awa_storages_model.png] -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012, 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 Ada.Strings.Unbounded; with Ada.Finalization; with ADO; -- = Storages Module = -- The `storages` module provides a set of storage services allowing -- an application to store data files, documents, images in a persistent area. -- The persistent store can be on a file system, in the database or provided -- by a remote service such as Amazon Simple Storage Service. -- -- @include awa-storages-modules.ads -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. -- The data itself can be physically stored in a file system (`FILE` mode), -- in the database (`DATABASE` mode) or on a remote server (`URL` mode). -- To put a file in the storage space, first create the storage object -- instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses -- this information to save the data in a file, in the database or in -- a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the -- storage service. -- It will read the file and put in in the corresponding persistent store -- (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated -- a unique identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been -- designed to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able -- to read the file. If the storage mode of the data is `FILE`, the path -- of the file on the storage file system is used. For other storage modes, -- the file is saved in a temporary file. In that case the `Store_Local` -- database table is used to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream -- connection is the most efficient mechanism. -- -- == Local file == -- To access the data by using a local file, we must define a local storage -- reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading -- locally we also indicate whether the file will be read or written. A file -- that is in `READ` mode can be shared by several tasks or processes. -- A file that is in `WRITE` mode will have a specific copy for the caller. -- An optional expiration parameter indicate when the local file representation -- can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- @include awa-storages-services.ads -- -- == Ada Beans == -- @include-bean storages.xml -- @include-bean storage-list.xml -- @include-bean folder-queries.xml -- @include-bean storage-queries.xml -- -- @include awa-storages-servlets.ads -- -- == Queries == -- @include-query storage-list.xml -- @include-query folder-queries.xml -- @include-query storage-queries.xml -- @include-query storage-info.xml -- -- == Data model == -- [images/awa_storages_model.png] -- package AWA.Storages is type Storage_Type is (DATABASE, FILE, URL, CACHE, TMP); type Storage_File (Storage : Storage_Type) is tagged limited private; -- Get the path to get access to the file. function Get_Path (File : in Storage_File) return String; -- Set the file path for the FILE, URL, CACHE or TMP storage. procedure Set (File : in out Storage_File; Path : in String); -- Set the file database storage identifier. procedure Set (File : in out Storage_File; Workspace : in ADO.Identifier; Store : in ADO.Identifier); private type Storage_File (Storage : Storage_Type) is limited new Ada.Finalization.Limited_Controlled with record case Storage is when DATABASE => Workspace : ADO.Identifier; Store : ADO.Identifier; when FILE | URL | CACHE | TMP => Path : Ada.Strings.Unbounded.Unbounded_String; end case; end record; overriding procedure Finalize (File : in out Storage_File); end AWA.Storages;
Add more documentation
Add more documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
efd203b9d2abee6bd0d57ee00379e4c8edd195da
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- 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 System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); procedure Skip (Msg : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- 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 System; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Fix definition of Skip procedure
Fix definition of Skip procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7cd900d0f7b9a98dd93344560c8d235bcdf3ab66
awa/plugins/awa-changelogs/src/awa-changelogs-modules.ads
awa/plugins/awa-changelogs/src/awa-changelogs-modules.ads
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with AWA.Modules; package AWA.Changelogs.Modules is -- The name under which the module is registered. NAME : constant String := "changelogs"; -- ------------------------------ -- Module changelogs -- ------------------------------ type Changelog_Module is new AWA.Modules.Module with private; type Changelog_Module_Access is access all Changelog_Module'Class; -- Initialize the changelogs module. overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the changelogs module. function Get_Changelog_Module return Changelog_Module_Access; private type Changelog_Module is new AWA.Modules.Module with null record; end AWA.Changelogs.Modules;
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; package AWA.Changelogs.Modules is -- The name under which the module is registered. NAME : constant String := "changelogs"; -- ------------------------------ -- Module changelogs -- ------------------------------ type Changelog_Module is new AWA.Modules.Module with private; type Changelog_Module_Access is access all Changelog_Module'Class; -- Initialize the changelogs module. overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the changelogs module. function Get_Changelog_Module return Changelog_Module_Access; -- Add the log message and associate it with the database entity identified by -- the given id and the entity type. The log message is associated with the current user. procedure Add_Log (Model : in Changelog_Module; Id : in ADO.Identifier; Entity_Type : in String; Message : in String); private type Changelog_Module is new AWA.Modules.Module with null record; end AWA.Changelogs.Modules;
Declare the Add_Log procedure
Declare the Add_Log procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1a50fc2f9978f972a6b8574ca8da347d79949277
mat/src/gtk/mat-consoles-gtkmat.ads
mat/src/gtk/mat-consoles-gtkmat.ads
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Glib; with Gtk.Frame; with Gtk.List_Store; with Gtk.Tree_Model; with Gtk.Cell_Renderer_Text; with Gtk.Tree_View; with Gtk.Scrolled_Window; package MAT.Consoles.Gtkmat is type Console_Type is new MAT.Consoles.Console_Type with private; type Console_Type_Access is access all Console_Type'Class; -- Initialize the console to display the result in the Gtk frame. procedure Initialize (Console : in out Console_Type; Frame : in Gtk.Frame.Gtk_Frame); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Column_Type is record Field : Field_Type; Title : Ada.Strings.Unbounded.Unbounded_String; end record; type Column_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Column_Type; type Field_Index_Array is array (Field_Type) of Glib.Gint; type Console_Type is new MAT.Consoles.Console_Type with record Frame : Gtk.Frame.Gtk_Frame; Scrolled : Gtk.Scrolled_Window.Gtk_Scrolled_Window; List : Gtk.List_Store.Gtk_List_Store; Current_Row : Gtk.Tree_Model.Gtk_Tree_Iter; File : Ada.Text_IO.File_Type; Indexes : Field_Index_Array; Columns : Column_Array; Tree : Gtk.Tree_View.Gtk_Tree_View; Col_Text : Gtk.Cell_Renderer_Text.Gtk_Cell_renderer_Text; end record; end MAT.Consoles.Gtkmat;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Glib; with Gtk.Frame; with Gtk.List_Store; with Gtk.Tree_Model; with Gtk.Cell_Renderer_Text; with Gtk.Tree_View; with Gtk.Scrolled_Window; package MAT.Consoles.Gtkmat is type Console_Type is new MAT.Consoles.Console_Type with private; type Console_Type_Access is access all Console_Type'Class; -- Initialize the console to display the result in the Gtk frame. procedure Initialize (Console : in out Console_Type; Frame : in Gtk.Frame.Gtk_Frame); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Column_Type is record Field : Field_Type; Title : Ada.Strings.Unbounded.Unbounded_String; end record; type Column_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Column_Type; type Field_Index_Array is array (Field_Type) of Glib.Gint; type Console_Type is new MAT.Consoles.Console_Type with record Frame : Gtk.Frame.Gtk_Frame; Scrolled : Gtk.Scrolled_Window.Gtk_Scrolled_Window; List : Gtk.List_Store.Gtk_List_Store; Current_Row : Gtk.Tree_Model.Gtk_Tree_Iter; File : Ada.Text_IO.File_Type; Indexes : Field_Index_Array; Columns : Column_Array; Tree : Gtk.Tree_View.Gtk_Tree_View; Col_Text : Gtk.Cell_Renderer_Text.Gtk_Cell_renderer_Text; end record; end MAT.Consoles.Gtkmat;
Add a Justify parameter to the Print_Field procedure
Add a Justify parameter to the Print_Field procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
064b520657b0607f47bd83ebc7a3d989707b9024
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Fix XML generation if a message contains a " (double quote). This terminates the attribute...
Fix XML generation if a message contains a " (double quote). This terminates the attribute...
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d56a006320a15a15577cc7f1f1879acbb35624a1
src/asf-sessions-factory.adb
src/asf-sessions-factory.adb
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; use Interfaces; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Lock.Write; -- Generate the random sequence. for I in 0 .. Factory.Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Factory.Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; Factory.Lock.Release_Write; -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record; begin Impl.Ref_Counter := Util.Concurrent.Counters.ONE; Impl.Create_Time := Ada.Calendar.Clock; Impl.Access_Time := Impl.Create_Time; Impl.Max_Inactive := Factory.Max_Inactive; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Lock.Write; Factory.Sessions.Insert (Impl.Id.all'Access, Sess); Factory.Lock.Release_Write; Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Null_Session; Factory.Lock.Read; declare Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then Result := Session_Maps.Element (Pos); end if; end; Factory.Lock.Release_Read; if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Id_Random.Reset (Factory.Random); end Initialize; end ASF.Sessions.Factory;
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; use Interfaces; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Lock.Write; -- Generate the random sequence. for I in 0 .. Factory.Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Factory.Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; Factory.Lock.Release_Write; -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record '(Ada.Finalization.Limited_Controlled with Ref_Counter => Util.Concurrent.Counters.ONE, Create_Time => Ada.Calendar.Clock, Max_Inactive => Factory.Max_Inactive, others => <>); begin Impl.Access_Time := Impl.Create_Time; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Lock.Write; Factory.Sessions.Insert (Impl.Id.all'Access, Sess); Factory.Lock.Release_Write; Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Null_Session; Factory.Lock.Read; declare Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then Result := Session_Maps.Element (Pos); end if; end; Factory.Lock.Release_Read; if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Id_Random.Reset (Factory.Random); end Initialize; end ASF.Sessions.Factory;
Fix compilation on arm
Fix compilation on arm
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a6062a114fc06d2983b37f64a0d184c58b141a33
src/ado-sequences-hilo.ads
src/ado-sequences-hilo.ads
----------------------------------------------------------------------- -- ADO Sequences Hilo-- HiLo Database sequence generator -- 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. ----------------------------------------------------------------------- -- The HiLo sequence generator. This sequence generator uses a database table -- <b>sequence</b> to allocate blocks of identifiers for a given sequence name. -- The sequence table contains one row for each sequence. It keeps track of -- the next available sequence identifier (in the <b>value</b> column). -- -- To allocate a sequence block, the HiLo generator obtains the next available -- sequence identified and updates it by adding the sequence block size. The -- HiLo sequence generator will allocate the identifiers until the block is -- full after which a new block will be allocated. package ADO.Sequences.Hilo is -- ------------------------------ -- High Low sequence generator -- ------------------------------ type HiLoGenerator is new Generator with private; DEFAULT_BLOCK_SIZE : constant Identifier := 100; -- Allocate an identifier using the generator. -- The generator allocates blocks of sequences by using a sequence -- table stored in the database. One database access is necessary -- every N allocations. overriding procedure Allocate (Gen : in out HiLoGenerator; Id : in out Objects.Object_Record'Class); -- Allocate a new sequence block. procedure Allocate_Sequence (Gen : in out HiLoGenerator); function Create_HiLo_Generator (Sess_Factory : in Session_Factory_Access) return Generator_Access; private type HiLoGenerator is new Generator with record Last_Id : Identifier := NO_IDENTIFIER; Next_Id : Identifier := NO_IDENTIFIER; Block_Size : Identifier := DEFAULT_BLOCK_SIZE; end record; end ADO.Sequences.Hilo;
----------------------------------------------------------------------- -- ADO Sequences Hilo-- HiLo Database sequence generator -- 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. ----------------------------------------------------------------------- -- === HiLo Sequence Generator === -- The HiLo sequence generator. This sequence generator uses a database table -- <b>sequence</b> to allocate blocks of identifiers for a given sequence name. -- The sequence table contains one row for each sequence. It keeps track of -- the next available sequence identifier (in the <b>value</b> column). -- -- To allocate a sequence block, the HiLo generator obtains the next available -- sequence identified and updates it by adding the sequence block size. The -- HiLo sequence generator will allocate the identifiers until the block is -- full after which a new block will be allocated. package ADO.Sequences.Hilo is -- ------------------------------ -- High Low sequence generator -- ------------------------------ type HiLoGenerator is new Generator with private; DEFAULT_BLOCK_SIZE : constant Identifier := 100; -- Allocate an identifier using the generator. -- The generator allocates blocks of sequences by using a sequence -- table stored in the database. One database access is necessary -- every N allocations. overriding procedure Allocate (Gen : in out HiLoGenerator; Id : in out Objects.Object_Record'Class); -- Allocate a new sequence block. procedure Allocate_Sequence (Gen : in out HiLoGenerator); function Create_HiLo_Generator (Sess_Factory : in Session_Factory_Access) return Generator_Access; private type HiLoGenerator is new Generator with record Last_Id : Identifier := NO_IDENTIFIER; Next_Id : Identifier := NO_IDENTIFIER; Block_Size : Identifier := DEFAULT_BLOCK_SIZE; end record; end ADO.Sequences.Hilo;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
6fe7fd18443bed28efcd437e2d2cc1634e2805f8
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [-web] [-tool] [-ado] " & "NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the GNU license or"); Put_Line (" a proprietary license. The author's name and email addresses"); Put_Line (" are also reported in generated files."); New_Line; Put_Line (" -web Generate a Web application"); Put_Line (" -tool Generate a command line tool"); Put_Line (" -ado Generate a database tool operation for ADO"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [--web] [--tool] [--ado] " & "NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the GNU license or"); Put_Line (" a proprietary license. The author's name and email addresses"); Put_Line (" are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); end Help; end Gen.Commands.Project;
Update the create-project help message
Update the create-project help message
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
ce6fff1f2b1a2441c72fa1ff09dd668891fcdaf9
src/util-serialize-tools.adb
src/util-serialize-tools.adb
----------------------------------------------------------------------- -- 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 Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.IO.JSON; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); Object_Mapping : aliased Object_Mapper.Mapper; procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => "params", Length => Map.Length); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array; end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML 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 is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Output : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Output.Start_Document; To_JSON (Output, Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- which their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : aliased Util.Beans.Objects.Maps.Map; Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin Context.Map := Result'Unchecked_Access; Parser.Add_Mapping ("params", Object_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse (Content); return Result; end From_JSON; begin Object_Mapping.Add_Mapping ("param/@name", FIELD_NAME); Object_Mapping.Add_Mapping ("param", FIELD_VALUE); end Util.Serialize.Tools;
----------------------------------------------------------------------- -- 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 Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.IO.JSON; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); Object_Mapping : aliased Object_Mapper.Mapper; procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => "params", Length => Map.Length); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array; end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML 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 is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Output : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Output.Start_Document; To_JSON (Output, Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- which their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : aliased Util.Beans.Objects.Maps.Map; Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Result'Unchecked_Access; Parser.Add_Mapping ("/params", Object_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse_String (Content); end if; return Result; end From_JSON; begin Object_Mapping.Add_Mapping ("name", FIELD_NAME); Object_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
Fix JSON deserialization into an object map
Fix JSON deserialization into an object map
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d17807a98a82568af43f99eda724efbfe0e1b1f5
src/base/log/util-log-appenders.ads
src/base/log/util-log-appenders.ads
----------------------------------------------------------------------- -- util-log-appenders -- Log appenders -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Util.Properties; limited with Util.Log.Loggers; -- The log <b>Appender</b> will handle the low level operations to write -- the log content to a file, the console, a database. package Util.Log.Appenders is use Ada.Strings.Unbounded; -- ------------------------------ -- Log event -- ------------------------------ -- The <b>Log_Event</b> represent a log message reported by one of the -- <b>log</b> operation (Debug, Info, Warn, Error). type Log_Event is record -- The log message (formatted) Message : Unbounded_String; -- The timestamp when the message was produced. Time : Ada.Calendar.Time; -- The log level Level : Level_Type; -- The logger Logger : access Util.Log.Loggers.Logger_Info; end record; -- The layout type to indicate how to format the message. -- Unlike Logj4, there is no customizable layout. type Layout_Type is ( -- The <b>message</b> layout with only the log message. -- Ex: "Cannot open file" MESSAGE, -- The <b>level-message</b> layout with level and message. -- Ex: "ERROR: Cannot open file" LEVEL_MESSAGE, -- The <b>date-level-message</b> layout with date -- Ex: "2011-03-04 12:13:34 ERROR: Cannot open file" DATE_LEVEL_MESSAGE, -- The <b>full</b> layout with everything (the default). -- Ex: "2011-03-04 12:13:34 ERROR - my.application - Cannot open file" FULL); -- ------------------------------ -- Log appender -- ------------------------------ type Appender is abstract new Ada.Finalization.Limited_Controlled with private; type Appender_Access is access all Appender'Class; -- Get the log level that triggers display of the log events function Get_Level (Self : in Appender) return Level_Type; -- Set the log level. procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type); -- Set the log layout format. procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type); -- Format the event into a string function Format (Self : in Appender; Event : in Log_Event) return String; -- Append a log event to the appender. Depending on the log level -- defined on the appender, the event can be taken into account or -- ignored. procedure Append (Self : in out Appender; Event : in Log_Event) is abstract; -- Flush the log events. procedure Flush (Self : in out Appender) is abstract; -- ------------------------------ -- File appender -- ------------------------------ -- Write log events to a file type File_Appender is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Event : in Log_Event); -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- Console appender -- ------------------------------ -- Write log events to the console type Console_Appender is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- List appender -- ------------------------------ -- Write log events to a list of appenders type List_Appender is new Appender with private; type List_Appender_Access is access all List_Appender'Class; -- Max number of appenders that can be added to the list. -- In most cases, 2 or 3 appenders will be used. MAX_APPENDERS : constant Natural := 10; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out List_Appender); -- Add the appender to the list. procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access); -- Create a list appender and configure it according to the properties function Create_List_Appender return List_Appender_Access; private type Appender is abstract new Ada.Finalization.Limited_Controlled with record Level : Level_Type := INFO_LEVEL; Layout : Layout_Type := FULL; end record; type File_Appender is new Appender with record Output : Ada.Text_IO.File_Type; Immediate_Flush : Boolean := False; end record; type Appender_Array_Access is array (1 .. MAX_APPENDERS) of Appender_Access; type List_Appender is new Appender with record Appenders : Appender_Array_Access; Count : Natural := 0; end record; type Console_Appender is new Appender with null record; end Util.Log.Appenders;
----------------------------------------------------------------------- -- util-log-appenders -- Log appenders -- Copyright (C) 2001 - 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.Text_IO; with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Util.Properties; limited with Util.Log.Loggers; -- The log <b>Appender</b> will handle the low level operations to write -- the log content to a file, the console, a database. package Util.Log.Appenders is use Ada.Strings.Unbounded; -- ------------------------------ -- Log event -- ------------------------------ -- The <b>Log_Event</b> represent a log message reported by one of the -- <b>log</b> operation (Debug, Info, Warn, Error). type Log_Event is record -- The log message (formatted) Message : Unbounded_String; -- The timestamp when the message was produced. Time : Ada.Calendar.Time; -- The log level Level : Level_Type; -- The logger Logger : access Util.Log.Loggers.Logger_Info; end record; -- The layout type to indicate how to format the message. -- Unlike Logj4, there is no customizable layout. type Layout_Type is ( -- The <b>message</b> layout with only the log message. -- Ex: "Cannot open file" MESSAGE, -- The <b>level-message</b> layout with level and message. -- Ex: "ERROR: Cannot open file" LEVEL_MESSAGE, -- The <b>date-level-message</b> layout with date -- Ex: "2011-03-04 12:13:34 ERROR: Cannot open file" DATE_LEVEL_MESSAGE, -- The <b>full</b> layout with everything (the default). -- Ex: "2011-03-04 12:13:34 ERROR - my.application - Cannot open file" FULL); -- ------------------------------ -- Log appender -- ------------------------------ type Appender is abstract new Ada.Finalization.Limited_Controlled with private; type Appender_Access is access all Appender'Class; -- Get the log level that triggers display of the log events function Get_Level (Self : in Appender) return Level_Type; -- Set the log level. procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type); -- Set the log layout format. procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type); -- Format the event into a string function Format (Self : in Appender; Event : in Log_Event) return String; -- Append a log event to the appender. Depending on the log level -- defined on the appender, the event can be taken into account or -- ignored. procedure Append (Self : in out Appender; Event : in Log_Event) is abstract; -- Flush the log events. procedure Flush (Self : in out Appender) is abstract; -- ------------------------------ -- File appender -- ------------------------------ -- Write log events to a file type File_Appender is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Event : in Log_Event); -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- Console appender -- ------------------------------ -- Write log events to the console type Console_Appender is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- List appender -- ------------------------------ -- Write log events to a list of appenders type List_Appender is new Appender with private; type List_Appender_Access is access all List_Appender'Class; -- Max number of appenders that can be added to the list. -- In most cases, 2 or 3 appenders will be used. MAX_APPENDERS : constant Natural := 10; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out List_Appender); -- Add the appender to the list. procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access); -- Create a list appender and configure it according to the properties function Create_List_Appender return List_Appender_Access; private type Appender is abstract new Ada.Finalization.Limited_Controlled with record Level : Level_Type := INFO_LEVEL; Layout : Layout_Type := FULL; end record; type File_Appender is new Appender with record Output : Ada.Text_IO.File_Type; Immediate_Flush : Boolean := False; end record; type Appender_Array_Access is array (1 .. MAX_APPENDERS) of Appender_Access; type List_Appender is new Appender with record Appenders : Appender_Array_Access; Count : Natural := 0; end record; type Console_Appender is new Appender with record Output : Ada.Text_IO.File_Access; end record; end Util.Log.Appenders;
Add Output member to the console appender
Add Output member to the console appender
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a9acd71d42f105b246713c364fd4fe4d2d31c2db
src/security-oauth-jwt.ads
src/security-oauth-jwt.ads
----------------------------------------------------------------------- -- security-oauth-jwt -- OAuth Java Web Token -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Properties; -- === JSON Web Token === -- JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred -- between two parties. A JWT token is returned by an authorization server. It contains -- useful information that allows to verify the authentication and identify the user. -- -- The <tt>Security.OAuth.JWT</tt> package implements the decoding part of JWT defined in: -- JSON Web Token (JWT), http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-07 -- -- A list of pre-defined ID tokens are returned in the JWT token claims and used for -- the OpenID Connect. This is specified in -- OpenID Connect Basic Client Profile 1.0 - draft 26, -- http://openid.net/specs/openid-connect-basic-1_0.html -- package Security.OAuth.JWT is -- Exception raised if the encoded token is invalid or cannot be decoded. Invalid_Token : exception; type Token is private; -- Get the issuer claim from the token (the "iss" claim). function Get_Issuer (From : in Token) return String; -- Get the subject claim from the token (the "sub" claim). function Get_Subject (From : in Token) return String; -- Get the audience claim from the token (the "aud" claim). function Get_Audience (From : in Token) return String; -- Get the expiration claim from the token (the "exp" claim). function Get_Expiration (From : in Token) return Ada.Calendar.Time; -- Get the not before claim from the token (the "nbf" claim). function Get_Not_Before (From : in Token) return Ada.Calendar.Time; -- Get the issued at claim from the token (the "iat" claim). -- This is the time when the JWT was issued. function Get_Issued_At (From : in Token) return Ada.Calendar.Time; -- Get the authentication time claim from the token (the "auth_time" claim). function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time; -- Get the JWT ID claim from the token (the "jti" claim). function Get_JWT_ID (From : in Token) return String; -- Get the authorized clients claim from the token (the "azp" claim). function Get_Authorized_Presenters (From : in Token) return String; -- Get the claim with the given name from the token. function Get_Claim (From : in Token; Name : in String) return String; -- Decode a string representing an encoded JWT token according to the JWT specification: -- -- Section 7. Rules for Creating and Validating a JWT -- -- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' . -- The first part represents the header, the second part the claims and the last part -- the signature. The <tt>Decode</tt> operation splits the parts, decodes them, -- parses the JSON content represented by the header and the claims. -- The <tt>Decode</tt> operation does not verify the signature (yet!). -- -- Return the decoded token or raise an exception. function Decode (Content : in String) return Token; private type Claims is new Util.Properties.Manager with null record; type Token is record Header : Util.Properties.Manager; Claims : Util.Properties.Manager; end record; end Security.OAuth.JWT;
----------------------------------------------------------------------- -- security-oauth-jwt -- OAuth Java Web Token -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Properties; -- === JSON Web Token === -- JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred -- between two parties. A JWT token is returned by an authorization server. It contains -- useful information that allows to verify the authentication and identify the user. -- -- The <tt>Security.OAuth.JWT</tt> package implements the decoding part of JWT defined in: -- JSON Web Token (JWT), http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-07 -- -- A list of pre-defined ID tokens are returned in the JWT token claims and used for -- the OpenID Connect. This is specified in -- OpenID Connect Basic Client Profile 1.0 - draft 26, -- http://openid.net/specs/openid-connect-basic-1_0.html -- package Security.OAuth.JWT is -- Exception raised if the encoded token is invalid or cannot be decoded. Invalid_Token : exception; type Token is private; -- Get the issuer claim from the token (the "iss" claim). function Get_Issuer (From : in Token) return String; -- Get the subject claim from the token (the "sub" claim). function Get_Subject (From : in Token) return String; -- Get the audience claim from the token (the "aud" claim). function Get_Audience (From : in Token) return String; -- Get the expiration claim from the token (the "exp" claim). function Get_Expiration (From : in Token) return Ada.Calendar.Time; -- Get the not before claim from the token (the "nbf" claim). function Get_Not_Before (From : in Token) return Ada.Calendar.Time; -- Get the issued at claim from the token (the "iat" claim). -- This is the time when the JWT was issued. function Get_Issued_At (From : in Token) return Ada.Calendar.Time; -- Get the authentication time claim from the token (the "auth_time" claim). function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time; -- Get the JWT ID claim from the token (the "jti" claim). function Get_JWT_ID (From : in Token) return String; -- Get the authorized clients claim from the token (the "azp" claim). function Get_Authorized_Presenters (From : in Token) return String; -- Get the claim with the given name from the token. function Get_Claim (From : in Token; Name : in String; Default : in String := "") return String; -- Decode a string representing an encoded JWT token according to the JWT specification: -- -- Section 7. Rules for Creating and Validating a JWT -- -- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' . -- The first part represents the header, the second part the claims and the last part -- the signature. The <tt>Decode</tt> operation splits the parts, decodes them, -- parses the JSON content represented by the header and the claims. -- The <tt>Decode</tt> operation does not verify the signature (yet!). -- -- Return the decoded token or raise an exception. function Decode (Content : in String) return Token; private type Claims is new Util.Properties.Manager with null record; type Token is record Header : Util.Properties.Manager; Claims : Util.Properties.Manager; end record; end Security.OAuth.JWT;
Update Get_Claim to add a default value returned if the claim does not exist
Update Get_Claim to add a default value returned if the claim does not exist
Ada
apache-2.0
stcarrez/ada-security
a41029ffa75a311be28684bc36da87288561629f
tests/natools-s_expressions-templates-tests-integers.adb
tests/natools-s_expressions-templates-tests-integers.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Parsers; with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Integers.T; package body Natools.S_Expressions.Templates.Tests.Integers is procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String); procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String); -- Run Template with Value and compare the result with Expected ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Parser, Value); Output.Check_Stream (Test); end Test_Render; procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Defaults, Parser, Value); Output.Check_Stream (Test); end Test_Render; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Alignment (Report); Default_Format (Report); Explicit_Images (Report); Explicit_Sign (Report); Hexadecimal (Report); Overflow (Report); Parse_Errors (Report); Static_Hash_Map (Report); Explicit_Default_Format (Report); Prefix_And_Suffix (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Alignment (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "(width 5)", 0, " 0"); Test_Render (Test, "(width 5)(padding _)(align center)", 10, "_10__"); Test_Render (Test, "(width 5 10)(left-align)", 7, "7 "); Test_Render (Test, "(min-width 5)(right-align)", 2, " 2"); Test_Render (Test, "(width 5)(padding > <)(centered)", 4, ">>4<<"); Test_Render (Test, "(width 5)(left-padding ""["")(right-padding ""]"")(centered)", 126, "[126]"); Test_Render (Test, "(width 3)(centered)", 16, "16 "); Test_Render (Test, "(width 3)(centered)", 456, "456"); Test_Render (Test, "(width 3)(align left)", 567, "567"); Test_Render (Test, "(width 3)(align right)", 678, "678"); exception when Error : others => Test.Report_Exception (Error); end Alignment; procedure Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "", 42, "42"); exception when Error : others => Test.Report_Exception (Error); end Default_Format; procedure Explicit_Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Client-provided default format"); begin declare Default : Templates.Integers.Format; begin Default.Set_Minimum_Width (2); Default.Set_Left_Padding (To_Atom ("0")); Test_Render (Test, Default, "", 5, "05"); Test_Render (Test, Default, "", 12, "12"); Test_Render (Test, Default, "(padding 1: )", 7, " 7"); end; exception when Error : others => Test.Report_Exception (Error); end Explicit_Default_Format; procedure Explicit_Images (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit images in template"); begin Test_Render (Test, "(image (-2 two) (666 evil))", 10, "10"); Test_Render (Test, "(image (-2 two) (666 evil))", -2, "two"); Test_Render (Test, "(image (-2 two) (666 evil))", 666, "evil"); Test_Render (Test, "(image (-2 two) (666 evil) (-2))", -2, "-2"); Test_Render (Test, "(image (1 one))3:Two4:four", 1, "one"); Test_Render (Test, "(image (1 one))3:Two4:four", 2, "Two"); Test_Render (Test, "(image (1 one))3:Two4:four", 3, "four"); Test_Render (Test, "(image (1 one))3:Two4:four", 4, "4"); Test_Render (Test, "(image (invalid -))5:first", Integer'First, "first"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Images; procedure Explicit_Sign (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit sign specification"); begin Test_Render (Test, "(sign +)", 42, "+42"); Test_Render (Test, "(sign + _)", 42, "+42"); Test_Render (Test, "(sign + _)", -42, "_42"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Sign; procedure Hexadecimal (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Hexadecimal representation"); Hex_Spec : constant String := "(base 0 1 2 3 4 5 6 7 8 9 A B C D E F)"; begin Test_Render (Test, Hex_Spec, 8, "8"); Test_Render (Test, Hex_Spec, 16#BEE#, "BEE"); exception when Error : others => Test.Report_Exception (Error); end Hexadecimal; procedure Overflow (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Width overflow"); begin Test_Render (Test, "(width 3)", 10_000, ""); Test_Render (Test, "(max-width 4)", 10_000, ""); Test_Render (Test, "(max-width 3 ""[...]"")", 10_000, "[...]"); Test_Render (Test, "(width 2 3 ...)", 10_000, "..."); exception when Error : others => Test.Report_Exception (Error); end Overflow; procedure Parse_Errors (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin Test_Render (Test, "(invalid-command)", 1, "1"); Test_Render (Test, "(align)", 2, "2"); Test_Render (Test, "(align invalid)", 3, "3"); Test_Render (Test, "(padding)", 4, "4"); Test_Render (Test, "(left-padding)", 5, "5"); Test_Render (Test, "(right-padding)", 6, "6"); Test_Render (Test, "(signs)", 7, "7"); Test_Render (Test, "(width)", 8, "8"); Test_Render (Test, "(max-width)", 9, "9"); Test_Render (Test, "(min-width)", 10, "10"); exception when Error : others => Test.Report_Exception (Error); end Parse_Errors; procedure Prefix_And_Suffix (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); Ordinal : constant String := "(suffix 1:? (th (0 31)) (st 1 21 31) (nd 2 22) (rd 3 23) (0: 0))"; begin declare Format : Templates.Integers.Format; begin Format.Set_Prefix ((0, 9), To_Atom ("a")); Format.Set_Prefix ((-99, -10), To_Atom ("b")); Format.Set_Prefix ((50, 99), To_Atom ("c")); Format.Set_Prefix (0, To_Atom ("d")); Format.Set_Prefix (-10, To_Atom ("e")); Format.Set_Prefix (5, To_Atom ("f")); Format.Set_Prefix ((7, 52), To_Atom ("g")); Format.Set_Prefix ((-52, -49), To_Atom ("h")); Format.Set_Prefix ((-100, -90), To_Atom ("i")); Format.Remove_Prefix (8); Test_Render (Test, Format, "", -196, "-196"); Test_Render (Test, Format, "", -101, "-101"); Test_Render (Test, Format, "", -100, "i-100"); Test_Render (Test, Format, "", -90, "i-90"); Test_Render (Test, Format, "", -89, "b-89"); Test_Render (Test, Format, "", -53, "b-53"); Test_Render (Test, Format, "", -52, "h-52"); Test_Render (Test, Format, "", -49, "h-49"); Test_Render (Test, Format, "", -48, "b-48"); Test_Render (Test, Format, "", -11, "b-11"); Test_Render (Test, Format, "", -10, "e-10"); Test_Render (Test, Format, "", -9, "-9"); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "d0"); Test_Render (Test, Format, "", 1, "a1"); Test_Render (Test, Format, "", 4, "a4"); Test_Render (Test, Format, "", 5, "f5"); Test_Render (Test, Format, "", 6, "a6"); Test_Render (Test, Format, "", 7, "g7"); Test_Render (Test, Format, "", 8, "8"); Test_Render (Test, Format, "", 9, "g9"); Test_Render (Test, Format, "", 52, "g52"); Test_Render (Test, Format, "", 53, "c53"); Test_Render (Test, Format, "", 99, "c99"); Test_Render (Test, Format, "", 100, "100"); Test_Render (Test, Format, "", 192, "192"); end; declare Format : Templates.Integers.Format; begin Format.Set_Suffix ((0, 10), To_Atom ("th")); Format.Set_Suffix (1, To_Atom ("st")); Format.Remove_Suffix (0); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "0"); Test_Render (Test, Format, "", 1, "1st"); Test_Render (Test, Format, "", 4, "4th"); Test_Render (Test, Format, "", 10, "10th"); end; Test_Render (Test, Ordinal, -1, "-1?"); Test_Render (Test, Ordinal, 0, "0"); Test_Render (Test, Ordinal, 1, "1st"); Test_Render (Test, Ordinal, 2, "2nd"); Test_Render (Test, Ordinal, 3, "3rd"); Test_Render (Test, Ordinal, 4, "4th"); Test_Render (Test, "(prefix (a) (b invalid (9 5)))", 0, "0"); Test_Render (Test, "(prefix (c (invalid 5) (-1 invalid)))", 0, "0"); Test_Render (Test, "(prefix (d ((invalid) 5) (-1)) ())", 0, "0"); exception when Error : others => Test.Report_Exception (Error); end Prefix_And_Suffix; procedure Static_Hash_Map (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin if not Natools.Static_Maps.S_Expressions.Templates.Integers.T then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Static_Hash_Map; end Natools.S_Expressions.Templates.Tests.Integers;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Parsers; with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Integers.T; package body Natools.S_Expressions.Templates.Tests.Integers is procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String); procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String); -- Run Template with Value and compare the result with Expected ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Parser, Value); Output.Check_Stream (Test); end Test_Render; procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Defaults, Parser, Value); Output.Check_Stream (Test); end Test_Render; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Alignment (Report); Default_Format (Report); Explicit_Images (Report); Explicit_Sign (Report); Hexadecimal (Report); Overflow (Report); Parse_Errors (Report); Static_Hash_Map (Report); Explicit_Default_Format (Report); Prefix_And_Suffix (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Alignment (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "(width 5)", 0, " 0"); Test_Render (Test, "(width 5)(padding _)(align center)", 10, "_10__"); Test_Render (Test, "(width 5 10)(left-align)", 7, "7 "); Test_Render (Test, "(min-width 5)(right-align)", 2, " 2"); Test_Render (Test, "(width 5)(padding > <)(centered)", 4, ">>4<<"); Test_Render (Test, "(width 5)(left-padding ""["")(right-padding ""]"")(centered)", 126, "[126]"); Test_Render (Test, "(width 3)(centered)", 16, "16 "); Test_Render (Test, "(width 3)(centered)", 456, "456"); Test_Render (Test, "(width 3)(align left)", 567, "567"); Test_Render (Test, "(width 3)(align right)", 678, "678"); exception when Error : others => Test.Report_Exception (Error); end Alignment; procedure Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "", 42, "42"); exception when Error : others => Test.Report_Exception (Error); end Default_Format; procedure Explicit_Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Client-provided default format"); begin declare Default : Templates.Integers.Format; begin Default.Set_Minimum_Width (2); Default.Set_Left_Padding (To_Atom ("0")); Test_Render (Test, Default, "", 5, "05"); Test_Render (Test, Default, "", 12, "12"); Test_Render (Test, Default, "(padding 1: )", 7, " 7"); end; exception when Error : others => Test.Report_Exception (Error); end Explicit_Default_Format; procedure Explicit_Images (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit images in template"); begin Test_Render (Test, "(image (-2 two) (666 evil))", 10, "10"); Test_Render (Test, "(image (-2 two) (666 evil))", -2, "two"); Test_Render (Test, "(image (-2 two) (666 evil))", 666, "evil"); Test_Render (Test, "(image (-2 two) (666 evil) (-2))", -2, "-2"); Test_Render (Test, "(image (1 one))3:Two4:four", 1, "one"); Test_Render (Test, "(image (1 one))3:Two4:four", 2, "Two"); Test_Render (Test, "(image (1 one))3:Two4:four", 3, "four"); Test_Render (Test, "(image (1 one))3:Two4:four", 4, "4"); Test_Render (Test, "(image (invalid -))5:first", Integer'First, "first"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Images; procedure Explicit_Sign (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit sign specification"); begin Test_Render (Test, "(sign +)", 42, "+42"); Test_Render (Test, "(sign + _)", 42, "+42"); Test_Render (Test, "(sign + _)", -42, "_42"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Sign; procedure Hexadecimal (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Hexadecimal representation"); Hex_Spec : constant String := "(base 0 1 2 3 4 5 6 7 8 9 A B C D E F)"; begin Test_Render (Test, Hex_Spec, 8, "8"); Test_Render (Test, Hex_Spec, 16#BEE#, "BEE"); exception when Error : others => Test.Report_Exception (Error); end Hexadecimal; procedure Overflow (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Width overflow"); begin Test_Render (Test, "(width 3)", 10_000, ""); Test_Render (Test, "(max-width 4)", 10_000, ""); Test_Render (Test, "(max-width 3 ""[...]"")", 10_000, "[...]"); Test_Render (Test, "(width 2 3 ...)", 10_000, "..."); exception when Error : others => Test.Report_Exception (Error); end Overflow; procedure Parse_Errors (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin Test_Render (Test, "(invalid-command)", 1, "1"); Test_Render (Test, "(align)", 2, "2"); Test_Render (Test, "(align invalid)", 3, "3"); Test_Render (Test, "(padding)", 4, "4"); Test_Render (Test, "(left-padding)", 5, "5"); Test_Render (Test, "(right-padding)", 6, "6"); Test_Render (Test, "(signs)", 7, "7"); Test_Render (Test, "(width)", 8, "8"); Test_Render (Test, "(max-width)", 9, "9"); Test_Render (Test, "(min-width)", 10, "10"); exception when Error : others => Test.Report_Exception (Error); end Parse_Errors; procedure Prefix_And_Suffix (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); Ordinal : constant String := "(suffix 1:? (th (0 31)) (st 1 21 31) (nd 2 22) (rd 3 23) (0: 0))"; begin declare Format : Templates.Integers.Format; begin Format.Set_Prefix ((0, 9), To_Atom ("a")); Format.Set_Prefix ((-99, -10), To_Atom ("b")); Format.Set_Prefix ((50, 99), To_Atom ("c")); Format.Set_Prefix (0, To_Atom ("d")); Format.Set_Prefix (-10, To_Atom ("e")); Format.Set_Prefix (5, To_Atom ("f")); Format.Set_Prefix ((7, 52), To_Atom ("g")); Format.Set_Prefix ((-52, -49), To_Atom ("h")); Format.Set_Prefix ((-100, -90), To_Atom ("i")); Format.Remove_Prefix (8); Test_Render (Test, Format, "", -196, "-196"); Test_Render (Test, Format, "", -101, "-101"); Test_Render (Test, Format, "", -100, "i-100"); Test_Render (Test, Format, "", -90, "i-90"); Test_Render (Test, Format, "", -89, "b-89"); Test_Render (Test, Format, "", -53, "b-53"); Test_Render (Test, Format, "", -52, "h-52"); Test_Render (Test, Format, "", -49, "h-49"); Test_Render (Test, Format, "", -48, "b-48"); Test_Render (Test, Format, "", -11, "b-11"); Test_Render (Test, Format, "", -10, "e-10"); Test_Render (Test, Format, "", -9, "-9"); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "d0"); Test_Render (Test, Format, "", 1, "a1"); Test_Render (Test, Format, "", 4, "a4"); Test_Render (Test, Format, "", 5, "f5"); Test_Render (Test, Format, "", 6, "a6"); Test_Render (Test, Format, "", 7, "g7"); Test_Render (Test, Format, "", 8, "8"); Test_Render (Test, Format, "", 9, "g9"); Test_Render (Test, Format, "", 52, "g52"); Test_Render (Test, Format, "", 53, "c53"); Test_Render (Test, Format, "", 99, "c99"); Test_Render (Test, Format, "", 100, "100"); Test_Render (Test, Format, "", 192, "192"); end; declare Format : Templates.Integers.Format; begin Format.Set_Suffix ((0, 10), To_Atom ("th")); Format.Set_Suffix (1, To_Atom ("st")); Format.Remove_Suffix (0); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "0"); Test_Render (Test, Format, "", 1, "1st"); Test_Render (Test, Format, "", 4, "4th"); Test_Render (Test, Format, "", 10, "10th"); end; Test_Render (Test, Ordinal, -1, "-1?"); Test_Render (Test, Ordinal, 0, "0"); Test_Render (Test, Ordinal, 1, "1st"); Test_Render (Test, Ordinal, 2, "2nd"); Test_Render (Test, Ordinal, 3, "3rd"); Test_Render (Test, Ordinal, 4, "4th"); Test_Render (Test, "(prefix (a) (b invalid (9 5)))", 0, "0"); Test_Render (Test, "(prefix (c (invalid 5) (-1 invalid)))", 0, "0"); Test_Render (Test, "(prefix (d ((invalid) 5) (-1)) ())", 0, "0"); declare Format : Templates.Integers.Format; begin Format.Set_Minimum_Width (10); Format.Set_Suffix (1, To_Atom ("<sup>er</sup>"), 2); Format.Set_Prefix (10, To_Atom ("dix : ")); Test_Render (Test, Format, "", 5, " 5"); Test_Render (Test, Format, "", 1, " 1<sup>er</sup>"); Test_Render (Test, Format, "(centered)", 10, " dix : 10 "); Test_Render (Test, Format, "(suffix ((th 0) 7))", 7, " 7th"); end; exception when Error : others => Test.Report_Exception (Error); end Prefix_And_Suffix; procedure Static_Hash_Map (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin if not Natools.Static_Maps.S_Expressions.Templates.Integers.T then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Static_Hash_Map; end Natools.S_Expressions.Templates.Tests.Integers;
add tests for prefix and suffix width
s_expressions-templates-tests-integers: add tests for prefix and suffix width
Ada
isc
faelys/natools
4be0d8e4fdaa41dae68ea370ae1b2512c7b02073
src/util-dates.adb
src/util-dates.adb
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Arithmetic; package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; -- ------------------------------ -- Get a time representing the given date at 00:00:00. -- ------------------------------ function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Day_Start; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_Start (D); end Get_Day_Start; -- ------------------------------ -- Get a time representing the beginning of the week at 00:00:00. -- ------------------------------ function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin if Day = Ada.Calendar.Formatting.Monday then return T; else return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday)); end if; end Get_Week_Start; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_Start (D); end Get_Week_Start; -- ------------------------------ -- Get a time representing the beginning of the month at 00:00:00. -- ------------------------------ function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Ada.Calendar.Day_Number'First, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Month_Start; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_Start (D); end Get_Month_Start; end Util.Dates;
Implement the new functions Get_Day_Start, Get_Week_Start and Get_Month_Start
Implement the new functions Get_Day_Start, Get_Week_Start and Get_Month_Start
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6547ef0ac0dd77e1e875d359f44d28f78af07dce
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 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.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.Event_Id_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.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.Event_Id_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; 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, 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 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.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.Event_Id_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.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.Event_Id_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; 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;
Fix compilation warning with GNAT 2018
Fix compilation warning with GNAT 2018
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8e49e1d263f71de1e3ec0e400a8c7934a06e775d
src/gl/implementation/gl-enums.ads
src/gl/implementation/gl-enums.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Low_Level; private package GL.Enums is pragma Preelaborate; type Shader_Param is (Shader_Type, Delete_Status, Compile_Status, Info_Log_Length, Shader_Source_Length); type Program_Param is (Program_Binary_Retrievable_Hint, Program_Separable, Compute_Work_Group_Size, Program_Binary_Length, Geometry_Vertices_Out, Geometry_Input_Type, Geometry_Output_Type, Active_Uniform_Block_Max_Name_Length, Active_Uniform_Blocks, Delete_Status, Link_Status, Validate_Status, Info_Log_Length, Attached_Shaders, Active_Uniforms, Active_Uniform_Max_Length, Active_Attributes, Active_Attribute_Max_Length, Active_Atomic_Counter_Buffers); type Program_Set_Param is (Program_Binary_Retrievable_Hint, Program_Separable); type Program_Stage_Param is (Active_Subroutines, Active_Subroutine_Uniforms, Active_Subroutine_Uniform_Locations, Active_Subroutine_Max_Length, Active_Subroutine_Uniform_Max_Length); type Program_Pipeline_Param is (Active_Program, Fragment_Shader, Vertex_Shader, Validate_Status, Info_Log_Length, Geometry_Shader, Tess_Evaluation_Shader, Tess_Control_Shader); type Program_Interface is (Atomic_Counter_Buffer, Uniform, Uniform_Block, Program_Input, Program_Output, Buffer_Variable, Shader_Storage_Block, Vertex_Subroutine, Tess_Control_Subroutine, Tess_Evaluation_Subroutine, Geometry_Subroutine, Fragment_Subroutine, Compute_Subroutine, Vertex_Subroutine_Uniform, Tess_Control_Subroutine_Uniform, Tess_Evaluation_Subroutine_Uniform, Geometry_Subroutine_Uniform, Fragment_Subroutine_Uniform, Compute_Subroutine_Uniform); type Program_Interface_Param is (Active_Resources, Max_Name_Length, Max_Num_Active_Variables, Max_Num_Compatible_Subroutines); type Program_Resource_Param is (Num_Compatible_Subroutines, Compatible_Subroutines, Is_Per_Patch, Name_Length, Resource_Type, Array_Size, Offset, Block_Index, Array_Stride, Matrix_Stride, Is_Row_Major, Atomic_Counter_Buffer_Index, Buffer_Binding, Buffer_Data_Size, Num_Active_Variables, Active_Variables, Referenced_By_Vertex_Shader, Referenced_By_Tess_Control_Shader, Referenced_By_Tess_Evaluation_Shader, Referenced_By_Geometry_Shader, Referenced_By_Fragment_Shader, Referenced_By_Compute_Shader, Top_Level_Array_Size, Top_Level_Array_Stride, Location, Location_Index); type Program_Resource_Array is array (Positive range <>) of Program_Resource_Param; type Pixel_Store_Param is (Unpack_Swap_Bytes, Unpack_LSB_First, Unpack_Row_Length, Unpack_Skip_Rows, Unpack_Skip_Pixels, Unpack_Alignment, Pack_Swap_Bytes, Pack_LSB_First, Pack_Row_Length, Pack_Skip_Rows, Pack_Skip_Pixels, Pack_Alignment, Pack_Skip_Images, Pack_Image_Height, Unpack_Skip_Images, Unpack_Image_Height, Unpack_Compressed_Block_Width, Unpack_Compressed_Block_Height, Unpack_Compressed_Block_Depth, Unpack_Compressed_Block_Size, Pack_Compressed_Block_Width, Pack_Compressed_Block_Height, Pack_Compressed_Block_Depth, Pack_Compressed_Block_Size); -- Table 8.1 and 18.1 of the OpenGL specification type Buffer_Param is (Buffer_Immutable_Storage, Buffer_Storage_Flags, Buffer_Size, Buffer_Access, Buffer_Mapped, Buffer_Access_Flags, Buffer_Map_Length, Buffer_Map_Offset); type Buffer_Pointer_Param is (Buffer_Map_Pointer); type Framebuffer_Param is (Default_Width, Default_Height, Default_Layers, Default_Samples, Default_Fixed_Sample_Locations); ----------------------------------------------------------------------------- type Framebuffer_Kind is (Read, Draw); type Buffer_Kind is (Parameter_Buffer, Pixel_Pack_Buffer, Pixel_Unpack_Buffer, Uniform_Buffer, Draw_Indirect_Buffer, Shader_Storage_Buffer, Dispatch_Indirect_Buffer, Query_Buffer, Atomic_Counter_Buffer); type Only_Depth_Buffer is (Depth_Buffer); type Only_Stencil_Buffer is (Stencil_Buffer); type Only_Depth_Stencil_Buffer is (Depth_Stencil_Buffer); type Only_Color_Buffer is (Color_Buffer); private for Shader_Param use (Shader_Type => 16#8B4F#, Delete_Status => 16#8B80#, Compile_Status => 16#8B81#, Info_Log_Length => 16#8B84#, Shader_Source_Length => 16#8B88#); for Shader_Param'Size use Low_Level.Enum'Size; for Program_Param use (Program_Binary_Retrievable_Hint => 16#8257#, Program_Separable => 16#8258#, Compute_Work_Group_Size => 16#8267#, Program_Binary_Length => 16#8741#, Geometry_Vertices_Out => 16#8916#, Geometry_Input_Type => 16#8917#, Geometry_Output_Type => 16#8918#, Active_Uniform_Block_Max_Name_Length => 16#8A35#, Active_Uniform_Blocks => 16#8A36#, Delete_Status => 16#8B4F#, Link_Status => 16#8B82#, Validate_Status => 16#8B83#, Info_Log_Length => 16#8B84#, Attached_Shaders => 16#8B85#, Active_Uniforms => 16#8B86#, Active_Uniform_Max_Length => 16#8B87#, Active_Attributes => 16#8B89#, Active_Attribute_Max_Length => 16#8B8A#, Active_Atomic_Counter_Buffers => 16#92D9#); for Program_Param'Size use Low_Level.Enum'Size; for Program_Set_Param use (Program_Binary_Retrievable_Hint => 16#8257#, Program_Separable => 16#8258#); for Program_Set_Param'Size use Low_Level.Enum'Size; for Program_Stage_Param use (Active_Subroutines => 16#8DE5#, Active_Subroutine_Uniforms => 16#8DE6#, Active_Subroutine_Uniform_Locations => 16#8E47#, Active_Subroutine_Max_Length => 16#8E48#, Active_Subroutine_Uniform_Max_Length => 16#8E49#); for Program_Stage_Param'Size use Low_Level.Enum'Size; for Program_Pipeline_Param use (Active_Program => 16#8259#, Fragment_Shader => 16#8B30#, Vertex_Shader => 16#8B31#, Validate_Status => 16#8B83#, Info_Log_Length => 16#8B84#, Geometry_Shader => 16#8DD9#, Tess_Evaluation_Shader => 16#8E87#, Tess_Control_Shader => 16#8E88#); for Program_Pipeline_Param'Size use Low_Level.Enum'Size; for Program_Interface use (Atomic_Counter_Buffer => 16#92C0#, Uniform => 16#92E1#, Uniform_Block => 16#92E2#, Program_Input => 16#92E3#, Program_Output => 16#92E4#, Buffer_Variable => 16#92E5#, Shader_Storage_Block => 16#92E6#, Vertex_Subroutine => 16#92E8#, Tess_Control_Subroutine => 16#92E9#, Tess_Evaluation_Subroutine => 16#92EA#, Geometry_Subroutine => 16#92EB#, Fragment_Subroutine => 16#92EC#, Compute_Subroutine => 16#92ED#, Vertex_Subroutine_Uniform => 16#92EE#, Tess_Control_Subroutine_Uniform => 16#92EF#, Tess_Evaluation_Subroutine_Uniform => 16#92F0#, Geometry_Subroutine_Uniform => 16#92F1#, Fragment_Subroutine_Uniform => 16#92F2#, Compute_Subroutine_Uniform => 16#92F3#); for Program_Interface'Size use Low_Level.Enum'Size; for Program_Interface_Param use (Active_Resources => 16#92F5#, Max_Name_Length => 16#92F6#, Max_Num_Active_Variables => 16#92F7#, Max_Num_Compatible_Subroutines => 16#92F8#); for Program_Interface_Param'Size use Low_Level.Enum'Size; for Program_Resource_Param use (Num_Compatible_Subroutines => 16#8E4A#, Compatible_Subroutines => 16#8E4B#, Is_Per_Patch => 16#92E7#, Name_Length => 16#92F9#, Resource_Type => 16#92FA#, Array_Size => 16#92FB#, Offset => 16#92FC#, Block_Index => 16#92FD#, Array_Stride => 16#92FE#, Matrix_Stride => 16#92FF#, Is_Row_Major => 16#9300#, Atomic_Counter_Buffer_Index => 16#9301#, Buffer_Binding => 16#9302#, Buffer_Data_Size => 16#9303#, Num_Active_Variables => 16#9304#, Active_Variables => 16#9305#, Referenced_By_Vertex_Shader => 16#9306#, Referenced_By_Tess_Control_Shader => 16#9307#, Referenced_By_Tess_Evaluation_Shader => 16#9308#, Referenced_By_Geometry_Shader => 16#9309#, Referenced_By_Fragment_Shader => 16#930A#, Referenced_By_Compute_Shader => 16#930B#, Top_Level_Array_Size => 16#930C#, Top_Level_Array_Stride => 16#930D#, Location => 16#930E#, Location_Index => 16#930F#); for Program_Resource_Param'Size use Low_Level.Enum'Size; for Pixel_Store_Param use (Unpack_Swap_Bytes => 16#0CF0#, Unpack_LSB_First => 16#0CF1#, Unpack_Row_Length => 16#0CF2#, Unpack_Skip_Rows => 16#0CF3#, Unpack_Skip_Pixels => 16#0CF4#, Unpack_Alignment => 16#0CF5#, Pack_Swap_Bytes => 16#0D00#, Pack_LSB_First => 16#0D01#, Pack_Row_Length => 16#0D02#, Pack_Skip_Rows => 16#0D03#, Pack_Skip_Pixels => 16#0D04#, Pack_Alignment => 16#0D05#, Pack_Skip_Images => 16#806B#, Pack_Image_Height => 16#806C#, Unpack_Skip_Images => 16#806D#, Unpack_Image_Height => 16#806E#, Unpack_Compressed_Block_Width => 16#9127#, Unpack_Compressed_Block_Height => 16#9128#, Unpack_Compressed_Block_Depth => 16#9129#, Unpack_Compressed_Block_Size => 16#912A#, Pack_Compressed_Block_Width => 16#912B#, Pack_Compressed_Block_Height => 16#912C#, Pack_Compressed_Block_Depth => 16#912D#, Pack_Compressed_Block_Size => 16#912E#); for Pixel_Store_Param'Size use Low_Level.Enum'Size; for Buffer_Param use (Buffer_Immutable_Storage => 16#821F#, Buffer_Storage_Flags => 16#8220#, Buffer_Size => 16#8764#, Buffer_Access => 16#88BB#, Buffer_Mapped => 16#88BC#, Buffer_Access_Flags => 16#911F#, Buffer_Map_Length => 16#9120#, Buffer_Map_Offset => 16#9121#); for Buffer_Param'Size use Low_Level.Enum'Size; for Buffer_Pointer_Param use (Buffer_Map_Pointer => 16#88BD#); for Buffer_Pointer_Param'Size use Low_Level.Enum'Size; for Framebuffer_Param use (Default_Width => 16#9310#, Default_Height => 16#9311#, Default_Layers => 16#9312#, Default_Samples => 16#9313#, Default_Fixed_Sample_Locations => 16#9314#); for Framebuffer_Param'Size use Low_Level.Enum'Size; ----------------------------------------------------------------------------- for Framebuffer_Kind use (Read => 16#8CA8#, Draw => 16#8CA9#); for Framebuffer_Kind'Size use Low_Level.Enum'Size; for Buffer_Kind use (Parameter_Buffer => 16#80EE#, Pixel_Pack_Buffer => 16#88EB#, Pixel_Unpack_Buffer => 16#88EC#, Uniform_Buffer => 16#8A11#, Draw_Indirect_Buffer => 16#8F3F#, Shader_Storage_Buffer => 16#90D2#, Dispatch_Indirect_Buffer => 16#90EE#, Query_Buffer => 16#9192#, Atomic_Counter_Buffer => 16#92C0#); for Buffer_Kind'Size use Low_Level.Enum'Size; for Only_Depth_Buffer use (Depth_Buffer => 16#1801#); for Only_Depth_Buffer'Size use Low_Level.Enum'Size; for Only_Stencil_Buffer use (Stencil_Buffer => 16#1802#); for Only_Stencil_Buffer'Size use Low_Level.Enum'Size; for Only_Depth_Stencil_Buffer use (Depth_Stencil_Buffer => 16#84F9#); for Only_Depth_Stencil_Buffer'Size use Low_Level.Enum'Size; for Only_Color_Buffer use (Color_Buffer => 16#1800#); for Only_Color_Buffer'Size use Low_Level.Enum'Size; end GL.Enums;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Low_Level; private package GL.Enums is pragma Preelaborate; type Shader_Param is (Shader_Type, Delete_Status, Compile_Status, Info_Log_Length, Shader_Source_Length); type Program_Param is (Program_Binary_Retrievable_Hint, Program_Separable, Compute_Work_Group_Size, Program_Binary_Length, Geometry_Vertices_Out, Geometry_Input_Type, Geometry_Output_Type, Active_Uniform_Block_Max_Name_Length, Active_Uniform_Blocks, Delete_Status, Link_Status, Validate_Status, Info_Log_Length, Attached_Shaders, Active_Uniforms, Active_Uniform_Max_Length, Active_Attributes, Active_Attribute_Max_Length, Active_Atomic_Counter_Buffers); type Program_Set_Param is (Program_Binary_Retrievable_Hint, Program_Separable); type Program_Pipeline_Param is (Active_Program, Fragment_Shader, Vertex_Shader, Validate_Status, Info_Log_Length, Geometry_Shader, Tess_Evaluation_Shader, Tess_Control_Shader); type Program_Interface is (Atomic_Counter_Buffer, Uniform, Uniform_Block, Program_Input, Program_Output, Buffer_Variable, Shader_Storage_Block, Vertex_Subroutine, Tess_Control_Subroutine, Tess_Evaluation_Subroutine, Geometry_Subroutine, Fragment_Subroutine, Compute_Subroutine, Vertex_Subroutine_Uniform, Tess_Control_Subroutine_Uniform, Tess_Evaluation_Subroutine_Uniform, Geometry_Subroutine_Uniform, Fragment_Subroutine_Uniform, Compute_Subroutine_Uniform); type Program_Interface_Param is (Active_Resources, Max_Name_Length, Max_Num_Active_Variables, Max_Num_Compatible_Subroutines); type Program_Resource_Param is (Num_Compatible_Subroutines, Compatible_Subroutines, Is_Per_Patch, Name_Length, Resource_Type, Array_Size, Offset, Block_Index, Array_Stride, Matrix_Stride, Is_Row_Major, Atomic_Counter_Buffer_Index, Buffer_Binding, Buffer_Data_Size, Num_Active_Variables, Active_Variables, Referenced_By_Vertex_Shader, Referenced_By_Tess_Control_Shader, Referenced_By_Tess_Evaluation_Shader, Referenced_By_Geometry_Shader, Referenced_By_Fragment_Shader, Referenced_By_Compute_Shader, Top_Level_Array_Size, Top_Level_Array_Stride, Location, Location_Index); type Program_Resource_Array is array (Positive range <>) of Program_Resource_Param; type Pixel_Store_Param is (Unpack_Swap_Bytes, Unpack_LSB_First, Unpack_Row_Length, Unpack_Skip_Rows, Unpack_Skip_Pixels, Unpack_Alignment, Pack_Swap_Bytes, Pack_LSB_First, Pack_Row_Length, Pack_Skip_Rows, Pack_Skip_Pixels, Pack_Alignment, Pack_Skip_Images, Pack_Image_Height, Unpack_Skip_Images, Unpack_Image_Height, Unpack_Compressed_Block_Width, Unpack_Compressed_Block_Height, Unpack_Compressed_Block_Depth, Unpack_Compressed_Block_Size, Pack_Compressed_Block_Width, Pack_Compressed_Block_Height, Pack_Compressed_Block_Depth, Pack_Compressed_Block_Size); -- Table 8.1 and 18.1 of the OpenGL specification type Buffer_Param is (Buffer_Immutable_Storage, Buffer_Storage_Flags, Buffer_Size, Buffer_Access, Buffer_Mapped, Buffer_Access_Flags, Buffer_Map_Length, Buffer_Map_Offset); type Buffer_Pointer_Param is (Buffer_Map_Pointer); type Framebuffer_Param is (Default_Width, Default_Height, Default_Layers, Default_Samples, Default_Fixed_Sample_Locations); ----------------------------------------------------------------------------- type Framebuffer_Kind is (Read, Draw); type Buffer_Kind is (Parameter_Buffer, Pixel_Pack_Buffer, Pixel_Unpack_Buffer, Uniform_Buffer, Draw_Indirect_Buffer, Shader_Storage_Buffer, Dispatch_Indirect_Buffer, Query_Buffer, Atomic_Counter_Buffer); type Only_Depth_Buffer is (Depth_Buffer); type Only_Stencil_Buffer is (Stencil_Buffer); type Only_Depth_Stencil_Buffer is (Depth_Stencil_Buffer); type Only_Color_Buffer is (Color_Buffer); private for Shader_Param use (Shader_Type => 16#8B4F#, Delete_Status => 16#8B80#, Compile_Status => 16#8B81#, Info_Log_Length => 16#8B84#, Shader_Source_Length => 16#8B88#); for Shader_Param'Size use Low_Level.Enum'Size; for Program_Param use (Program_Binary_Retrievable_Hint => 16#8257#, Program_Separable => 16#8258#, Compute_Work_Group_Size => 16#8267#, Program_Binary_Length => 16#8741#, Geometry_Vertices_Out => 16#8916#, Geometry_Input_Type => 16#8917#, Geometry_Output_Type => 16#8918#, Active_Uniform_Block_Max_Name_Length => 16#8A35#, Active_Uniform_Blocks => 16#8A36#, Delete_Status => 16#8B4F#, Link_Status => 16#8B82#, Validate_Status => 16#8B83#, Info_Log_Length => 16#8B84#, Attached_Shaders => 16#8B85#, Active_Uniforms => 16#8B86#, Active_Uniform_Max_Length => 16#8B87#, Active_Attributes => 16#8B89#, Active_Attribute_Max_Length => 16#8B8A#, Active_Atomic_Counter_Buffers => 16#92D9#); for Program_Param'Size use Low_Level.Enum'Size; for Program_Set_Param use (Program_Binary_Retrievable_Hint => 16#8257#, Program_Separable => 16#8258#); for Program_Set_Param'Size use Low_Level.Enum'Size; for Program_Pipeline_Param use (Active_Program => 16#8259#, Fragment_Shader => 16#8B30#, Vertex_Shader => 16#8B31#, Validate_Status => 16#8B83#, Info_Log_Length => 16#8B84#, Geometry_Shader => 16#8DD9#, Tess_Evaluation_Shader => 16#8E87#, Tess_Control_Shader => 16#8E88#); for Program_Pipeline_Param'Size use Low_Level.Enum'Size; for Program_Interface use (Atomic_Counter_Buffer => 16#92C0#, Uniform => 16#92E1#, Uniform_Block => 16#92E2#, Program_Input => 16#92E3#, Program_Output => 16#92E4#, Buffer_Variable => 16#92E5#, Shader_Storage_Block => 16#92E6#, Vertex_Subroutine => 16#92E8#, Tess_Control_Subroutine => 16#92E9#, Tess_Evaluation_Subroutine => 16#92EA#, Geometry_Subroutine => 16#92EB#, Fragment_Subroutine => 16#92EC#, Compute_Subroutine => 16#92ED#, Vertex_Subroutine_Uniform => 16#92EE#, Tess_Control_Subroutine_Uniform => 16#92EF#, Tess_Evaluation_Subroutine_Uniform => 16#92F0#, Geometry_Subroutine_Uniform => 16#92F1#, Fragment_Subroutine_Uniform => 16#92F2#, Compute_Subroutine_Uniform => 16#92F3#); for Program_Interface'Size use Low_Level.Enum'Size; for Program_Interface_Param use (Active_Resources => 16#92F5#, Max_Name_Length => 16#92F6#, Max_Num_Active_Variables => 16#92F7#, Max_Num_Compatible_Subroutines => 16#92F8#); for Program_Interface_Param'Size use Low_Level.Enum'Size; for Program_Resource_Param use (Num_Compatible_Subroutines => 16#8E4A#, Compatible_Subroutines => 16#8E4B#, Is_Per_Patch => 16#92E7#, Name_Length => 16#92F9#, Resource_Type => 16#92FA#, Array_Size => 16#92FB#, Offset => 16#92FC#, Block_Index => 16#92FD#, Array_Stride => 16#92FE#, Matrix_Stride => 16#92FF#, Is_Row_Major => 16#9300#, Atomic_Counter_Buffer_Index => 16#9301#, Buffer_Binding => 16#9302#, Buffer_Data_Size => 16#9303#, Num_Active_Variables => 16#9304#, Active_Variables => 16#9305#, Referenced_By_Vertex_Shader => 16#9306#, Referenced_By_Tess_Control_Shader => 16#9307#, Referenced_By_Tess_Evaluation_Shader => 16#9308#, Referenced_By_Geometry_Shader => 16#9309#, Referenced_By_Fragment_Shader => 16#930A#, Referenced_By_Compute_Shader => 16#930B#, Top_Level_Array_Size => 16#930C#, Top_Level_Array_Stride => 16#930D#, Location => 16#930E#, Location_Index => 16#930F#); for Program_Resource_Param'Size use Low_Level.Enum'Size; for Pixel_Store_Param use (Unpack_Swap_Bytes => 16#0CF0#, Unpack_LSB_First => 16#0CF1#, Unpack_Row_Length => 16#0CF2#, Unpack_Skip_Rows => 16#0CF3#, Unpack_Skip_Pixels => 16#0CF4#, Unpack_Alignment => 16#0CF5#, Pack_Swap_Bytes => 16#0D00#, Pack_LSB_First => 16#0D01#, Pack_Row_Length => 16#0D02#, Pack_Skip_Rows => 16#0D03#, Pack_Skip_Pixels => 16#0D04#, Pack_Alignment => 16#0D05#, Pack_Skip_Images => 16#806B#, Pack_Image_Height => 16#806C#, Unpack_Skip_Images => 16#806D#, Unpack_Image_Height => 16#806E#, Unpack_Compressed_Block_Width => 16#9127#, Unpack_Compressed_Block_Height => 16#9128#, Unpack_Compressed_Block_Depth => 16#9129#, Unpack_Compressed_Block_Size => 16#912A#, Pack_Compressed_Block_Width => 16#912B#, Pack_Compressed_Block_Height => 16#912C#, Pack_Compressed_Block_Depth => 16#912D#, Pack_Compressed_Block_Size => 16#912E#); for Pixel_Store_Param'Size use Low_Level.Enum'Size; for Buffer_Param use (Buffer_Immutable_Storage => 16#821F#, Buffer_Storage_Flags => 16#8220#, Buffer_Size => 16#8764#, Buffer_Access => 16#88BB#, Buffer_Mapped => 16#88BC#, Buffer_Access_Flags => 16#911F#, Buffer_Map_Length => 16#9120#, Buffer_Map_Offset => 16#9121#); for Buffer_Param'Size use Low_Level.Enum'Size; for Buffer_Pointer_Param use (Buffer_Map_Pointer => 16#88BD#); for Buffer_Pointer_Param'Size use Low_Level.Enum'Size; for Framebuffer_Param use (Default_Width => 16#9310#, Default_Height => 16#9311#, Default_Layers => 16#9312#, Default_Samples => 16#9313#, Default_Fixed_Sample_Locations => 16#9314#); for Framebuffer_Param'Size use Low_Level.Enum'Size; ----------------------------------------------------------------------------- for Framebuffer_Kind use (Read => 16#8CA8#, Draw => 16#8CA9#); for Framebuffer_Kind'Size use Low_Level.Enum'Size; for Buffer_Kind use (Parameter_Buffer => 16#80EE#, Pixel_Pack_Buffer => 16#88EB#, Pixel_Unpack_Buffer => 16#88EC#, Uniform_Buffer => 16#8A11#, Draw_Indirect_Buffer => 16#8F3F#, Shader_Storage_Buffer => 16#90D2#, Dispatch_Indirect_Buffer => 16#90EE#, Query_Buffer => 16#9192#, Atomic_Counter_Buffer => 16#92C0#); for Buffer_Kind'Size use Low_Level.Enum'Size; for Only_Depth_Buffer use (Depth_Buffer => 16#1801#); for Only_Depth_Buffer'Size use Low_Level.Enum'Size; for Only_Stencil_Buffer use (Stencil_Buffer => 16#1802#); for Only_Stencil_Buffer'Size use Low_Level.Enum'Size; for Only_Depth_Stencil_Buffer use (Depth_Stencil_Buffer => 16#84F9#); for Only_Depth_Stencil_Buffer'Size use Low_Level.Enum'Size; for Only_Color_Buffer use (Color_Buffer => 16#1800#); for Only_Color_Buffer'Size use Low_Level.Enum'Size; end GL.Enums;
Remove unused type Program_Stage_Param in package GL.Enums
gl: Remove unused type Program_Stage_Param in package GL.Enums Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
824e6154db356158cc5c5c2b9f8cd9bb16521273
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Update Verify to allow in out parameter for the realm
Update Verify to allow in out parameter for the realm
Ada
apache-2.0
stcarrez/ada-security
6814a9c265943ef86e2238d5225afb390317771c
src/os-linux/util-processes-os.adb
src/os-linux/util-processes-os.adb
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 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.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; pragma Unreferenced (Result); Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; if Mode = READ_ALL or Mode = READ_WRITE_ALL then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; if Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); elsif Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); Result := Sys_Close (Stdout_Pipes (1)); end if; Result := Sys_Close (Stdout_Pipes (0)); elsif Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); Result := Sys_Close (Stdin_Pipes (0)); end if; Result := Sys_Close (Stdin_Pipes (1)); elsif Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); end Finalize; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Unchecked_Deallocation; package body Util.Processes.Os is use Util.Systems.Os; use type Interfaces.C.size_t; use type Util.Systems.Types.File_Type; use type Ada.Directories.File_Kind; type Pipe_Type is array (0 .. 1) of File_Type; procedure Close (Pipes : in out Pipe_Type); -- ------------------------------ -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. -- ------------------------------ function Create_Stream (File : in File_Type) return Util.Streams.Raw.Raw_Stream_Access is Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream; Status : constant Integer := Sys_Fcntl (File, F_SETFL, FD_CLOEXEC); pragma Unreferenced (Status); begin Stream.Initialize (File); return Stream; end Create_Stream; -- ------------------------------ -- Wait for the process to exit. -- ------------------------------ overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is pragma Unreferenced (Sys, Timeout); use type Util.Streams.Output_Stream_Access; Result : Integer; Wpid : Integer; begin -- Close the input stream pipe if there is one. if Proc.Input /= null then Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close; end if; Wpid := Sys_Waitpid (Integer (Proc.Pid), Result'Address, 0); if Wpid = Integer (Proc.Pid) then Proc.Exit_Value := Result / 256; if Result mod 256 /= 0 then Proc.Exit_Value := (Result mod 256) * 1000; end if; end if; end Wait; -- ------------------------------ -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. -- ------------------------------ overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is pragma Unreferenced (Sys); Result : Integer; pragma Unreferenced (Result); begin Result := Sys_Kill (Integer (Proc.Pid), Integer (Signal)); end Stop; -- ------------------------------ -- Close both ends of the pipe (used to cleanup in case or error). -- ------------------------------ procedure Close (Pipes : in out Pipe_Type) is Result : Integer; pragma Unreferenced (Result); begin if Pipes (0) /= NO_FILE then Result := Sys_Close (Pipes (0)); Pipes (0) := NO_FILE; end if; if Pipes (1) /= NO_FILE then Result := Sys_Close (Pipes (1)); Pipes (1) := NO_FILE; end if; end Close; procedure Prepare_Working_Directory (Sys : in out System_Process; Proc : in out Process'Class) is Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir); begin Interfaces.C.Strings.Free (Sys.Dir); if Dir'Length > 0 then if not Ada.Directories.Exists (Dir) or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory then raise Ada.Directories.Name_Error with "Invalid directory: " & Dir; end if; Sys.Dir := Interfaces.C.Strings.New_String (Dir); end if; end Prepare_Working_Directory; -- ------------------------------ -- Spawn a new process. -- ------------------------------ overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is use Interfaces.C.Strings; use type Interfaces.C.int; procedure Cleanup; -- Suppress all checks to make sure the child process will not raise any exception. pragma Suppress (All_Checks); Result : Integer; pragma Unreferenced (Result); Stdin_Pipes : aliased Pipe_Type := (others => NO_FILE); Stdout_Pipes : aliased Pipe_Type := (others => NO_FILE); Stderr_Pipes : aliased Pipe_Type := (others => NO_FILE); procedure Cleanup is begin Close (Stdin_Pipes); Close (Stdout_Pipes); Close (Stderr_Pipes); end Cleanup; begin Sys.Prepare_Working_Directory (Proc); -- Since checks are disabled, verify by hand that the argv table is correct. if Sys.Argv = null or else Sys.Argc < 1 or else Sys.Argv (0) = Null_Ptr then raise Program_Error with "Invalid process argument list"; end if; -- Setup the pipes. if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then if Sys_Pipe (Stdout_Pipes'Address) /= 0 then raise Process_Error with "Cannot create stdout pipe"; end if; end if; if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then if Sys_Pipe (Stdin_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stdin pipe"; end if; end if; if Mode = READ_ERROR then if Sys_Pipe (Stderr_Pipes'Address) /= 0 then Cleanup; raise Process_Error with "Cannot create stderr pipe"; end if; end if; -- Create the new process by using vfork instead of fork. The parent process is blocked -- until the child executes the exec or exits. The child process uses the same stack -- as the parent. Proc.Pid := Sys_VFork; if Proc.Pid = 0 then -- Do not use any Ada type while in the child process. if Proc.To_Close /= null then for Fd of Proc.To_Close.all loop Result := Sys_Close (Fd); end loop; end if; if Mode = READ_ALL or Mode = READ_WRITE_ALL then Result := Sys_Dup2 (Stdout_Pipes (1), STDERR_FILENO); end if; if Stderr_Pipes (1) /= NO_FILE then if Stderr_Pipes (1) /= STDERR_FILENO then Result := Sys_Dup2 (Stderr_Pipes (1), STDERR_FILENO); Result := Sys_Close (Stderr_Pipes (1)); end if; Result := Sys_Close (Stderr_Pipes (0)); elsif Sys.Err_File /= Null_Ptr then -- Redirect the process error to a file. declare Fd : File_Type; begin if Sys.Err_Append then Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Err_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdout_Pipes (1) /= NO_FILE then if Stdout_Pipes (1) /= STDOUT_FILENO then Result := Sys_Dup2 (Stdout_Pipes (1), STDOUT_FILENO); Result := Sys_Close (Stdout_Pipes (1)); end if; Result := Sys_Close (Stdout_Pipes (0)); elsif Sys.Out_File /= Null_Ptr then -- Redirect the process output to a file. declare Fd : File_Type; begin if Sys.Out_Append then Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_APPEND, 8#644#); else Fd := Sys_Open (Sys.Out_File, O_CREAT + O_WRONLY + O_TRUNC, 8#644#); end if; if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDOUT_FILENO); Result := Sys_Close (Fd); end; end if; if Stdin_Pipes (0) /= NO_FILE then if Stdin_Pipes (0) /= STDIN_FILENO then Result := Sys_Dup2 (Stdin_Pipes (0), STDIN_FILENO); Result := Sys_Close (Stdin_Pipes (0)); end if; Result := Sys_Close (Stdin_Pipes (1)); elsif Sys.In_File /= Null_Ptr then -- Redirect the process input from a file. declare Fd : File_Type; begin Fd := Sys_Open (Sys.In_File, O_RDONLY, 8#644#); if Fd < 0 then Sys_Exit (254); end if; Result := Sys_Dup2 (Fd, STDIN_FILENO); Result := Sys_Close (Fd); end; end if; if Sys.Dir /= Null_Ptr then Result := Sys_Chdir (Sys.Dir); if Result < 0 then Sys_Exit (253); end if; end if; Result := Sys_Execvp (Sys.Argv (0), Sys.Argv.all); Sys_Exit (255); end if; -- Process creation failed, cleanup and raise an exception. if Proc.Pid < 0 then Cleanup; raise Process_Error with "Cannot create process"; end if; if Stdin_Pipes (1) /= NO_FILE then Result := Sys_Close (Stdin_Pipes (0)); Proc.Input := Create_Stream (Stdin_Pipes (1)).all'Access; end if; if Stdout_Pipes (0) /= NO_FILE then Result := Sys_Close (Stdout_Pipes (1)); Proc.Output := Create_Stream (Stdout_Pipes (0)).all'Access; end if; if Stderr_Pipes (0) /= NO_FILE then Result := Sys_Close (Stderr_Pipes (1)); Proc.Error := Create_Stream (Stderr_Pipes (0)).all'Access; end if; end Spawn; procedure Free is new Ada.Unchecked_Deallocation (Name => Ptr_Ptr_Array, Object => Ptr_Array); -- ------------------------------ -- Append the argument to the process argument list. -- ------------------------------ overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String) is begin if Sys.Argv = null then Sys.Argv := new Ptr_Array (0 .. 10); elsif Sys.Argc = Sys.Argv'Last - 1 then declare N : constant Ptr_Ptr_Array := new Ptr_Array (0 .. Sys.Argc + 32); begin N (0 .. Sys.Argc) := Sys.Argv (0 .. Sys.Argc); Free (Sys.Argv); Sys.Argv := N; end; end if; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.New_String (Arg); Sys.Argc := Sys.Argc + 1; Sys.Argv (Sys.Argc) := Interfaces.C.Strings.Null_Ptr; end Append_Argument; -- ------------------------------ -- Set the process input, output and error streams to redirect and use specified files. -- ------------------------------ overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is begin if Input'Length > 0 then Sys.In_File := Interfaces.C.Strings.New_String (Input); end if; if Output'Length > 0 then Sys.Out_File := Interfaces.C.Strings.New_String (Output); Sys.Out_Append := Append_Output; end if; if Error'Length > 0 then Sys.Err_File := Interfaces.C.Strings.New_String (Error); Sys.Err_Append := Append_Error; end if; Sys.To_Close := To_Close; end Set_Streams; -- ------------------------------ -- Deletes the storage held by the system process. -- ------------------------------ overriding procedure Finalize (Sys : in out System_Process) is begin if Sys.Argv /= null then for I in Sys.Argv'Range loop Interfaces.C.Strings.Free (Sys.Argv (I)); end loop; Free (Sys.Argv); end if; Interfaces.C.Strings.Free (Sys.In_File); Interfaces.C.Strings.Free (Sys.Out_File); Interfaces.C.Strings.Free (Sys.Err_File); Interfaces.C.Strings.Free (Sys.Dir); end Finalize; end Util.Processes.Os;
Implement Prepare_Working_Directory before the fork and use the prepared path to change the current working directory after the fork
Implement Prepare_Working_Directory before the fork and use the prepared path to change the current working directory after the fork
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b6e69f1e7d5460f992a4e9f67ad91bfce84af6c0
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; -- ------------------------------ -- 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; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_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, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body 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_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, 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; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_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;
Create the N_NEWLINE node in the document
Create the N_NEWLINE node in the document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
6db19f1da45c17e7d03a08c907eaf6c33d2a62ae
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; -- ------------------------------ -- 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;
----------------------------------------------------------------------- -- 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; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_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 Hide_TOC procedure to mark the table of content as hidden on the document
Implement Hide_TOC procedure to mark the table of content as hidden on the document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
637b408bc3b100bf2a4ff3dc094798107208e1c9
samples/print_user.adb
samples/print_user.adb
----------------------------------------------------------------------- -- Print_User -- Example to find an object from the database -- 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 ADO; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Print_User is use ADO; use Ada; use Samples.User.Model; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: print_user user-name ..."); Ada.Text_IO.Put_Line ("Example: print_user joe"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Create and configure the connection pool Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare Session : ADO.Sessions.Session := Factory.Get_Session; User : User_Ref; Found : Boolean; begin for I in 1 .. Ada.Command_Line.Argument_Count loop declare User_Name : constant String := Ada.Command_Line.Argument (I); Query : ADO.SQL.Query; begin Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'..."); Query.Bind_Param (1, User_Name); Query.Set_Filter ("name = ?"); User.Find (Session => Session, Query => Query, Found => Found); if Found then Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id)); Ada.Text_IO.Put_Line (" User : " & User.Get_Name); Ada.Text_IO.Put_Line (" Email : " & User.Get_Email); else Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist"); end if; end; end loop; end; end Print_User;
----------------------------------------------------------------------- -- Print_User -- Example to find an object from the database -- 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 ADO; with ADO.Drivers.Initializer; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Print_User is use ADO; use Ada; use Samples.User.Model; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: print_user user-name ..."); Ada.Text_IO.Put_Line ("Example: print_user joe"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Create and configure the connection pool Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare Session : ADO.Sessions.Session := Factory.Get_Session; User : User_Ref; Found : Boolean; begin for I in 1 .. Ada.Command_Line.Argument_Count loop declare User_Name : constant String := Ada.Command_Line.Argument (I); Query : ADO.SQL.Query; begin Ada.Text_IO.Put_Line ("Searching '" & User_Name & "'..."); Query.Bind_Param (1, User_Name); Query.Set_Filter ("name = ?"); User.Find (Session => Session, Query => Query, Found => Found); if Found then Ada.Text_IO.Put_Line (" Id : " & Identifier'Image (User.Get_Id)); Ada.Text_IO.Put_Line (" User : " & User.Get_Name); Ada.Text_IO.Put_Line (" Email : " & User.Get_Email); else Ada.Text_IO.Put_Line (" User '" & User_Name & "' does not exist"); end if; end; end loop; end; end Print_User;
Update driver registration and initialization
Update driver registration and initialization
Ada
apache-2.0
Letractively/ada-ado
ff2497a7dbb863c8e62f13e12ae238f89cd81f09
src/http/util-mail.adb
src/http/util-mail.adb
----------------------------------------------------------------------- -- util-mail -- Mail Utility Library -- 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.Strings.Fixed; package body Util.Mail is -- ------------------------------ -- Parse the email address and separate the name from the address. -- ------------------------------ function Parse_Address (E_Mail : in String) return Email_Address is use Ada.Strings.Unbounded; use Ada.Strings.Fixed; use Ada.Strings; Result : Email_Address; First_Pos : constant Natural := Index (E_Mail, "<"); Last_Pos : constant Natural := Index (E_Mail, ">"); At_Pos : constant Natural := Index (E_Mail, "@"); begin if First_Pos > 0 and Last_Pos > 0 then Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. First_Pos - 1), Both)); Result.Address := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. Last_Pos - 1), Both)); if Length (Result.Name) = 0 and At_Pos < Last_Pos then Result.Name := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. At_Pos - 1), Both)); end if; else Result.Address := To_Unbounded_String (Trim (E_Mail, Both)); Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. At_Pos - 1), Both)); end if; return Result; end Parse_Address; end Util.Mail;
----------------------------------------------------------------------- -- util-mail -- Mail Utility Library -- 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.Strings.Fixed; package body Util.Mail is use Ada.Strings.Unbounded; use Ada.Strings.Fixed; use Ada.Strings; -- ------------------------------ -- Parse the email address and separate the name from the address. -- ------------------------------ function Parse_Address (E_Mail : in String) return Email_Address is Result : Email_Address; First_Pos : constant Natural := Index (E_Mail, "<"); Last_Pos : constant Natural := Index (E_Mail, ">"); At_Pos : constant Natural := Index (E_Mail, "@"); begin if First_Pos > 0 and Last_Pos > 0 then Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. First_Pos - 1), Both)); Result.Address := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. Last_Pos - 1), Both)); if Length (Result.Name) = 0 and At_Pos < Last_Pos then Result.Name := To_Unbounded_String (Trim (E_Mail (First_Pos + 1 .. At_Pos - 1), Both)); end if; else Result.Address := To_Unbounded_String (Trim (E_Mail, Both)); Result.Name := To_Unbounded_String (Trim (E_Mail (E_Mail'First .. At_Pos - 1), Both)); end if; return Result; end Parse_Address; -- ------------------------------ -- Extract a first name from the email address. -- ------------------------------ function Get_First_Name (From : in Email_Address) return String is Name : constant String := To_String (From.Name); Pos : Natural := Index (Name, " "); begin if Pos > 0 then return Name (Name'First .. Pos - 1); end if; Pos := Index (Name, "."); if Pos > 0 then return Name (Name'First .. Pos - 1); else return ""; end if; end Get_First_Name; end Util.Mail;
Implement the Get_First_Name function to extract a possible first name from the email address
Implement the Get_First_Name function to extract a possible first name from the email address
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4080e60337fec8114469f515f28cedce6402d16b
src/http/aws/util-http-clients-web.adb
src/http/aws/util-http-clients-web.adb
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Client; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers); end Do_Put; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Client; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers); end Do_Put; -- Set the timeout for the connection. overriding procedure Set_Timeout (Manager : in AWS_Http_Manager; Http : in Client'Class; Timeout : in Duration) is begin null; end Set_Timeout; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
Implement the Set_Timeout procedure
Implement the Set_Timeout procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
75e8936523179ac3472822af4a5828b6130f724f
tools/druss-config.ads
tools/druss-config.ads
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Gateways; package Druss.Config is -- Initialize the configuration. procedure Initialize (Path : in String); -- Get the configuration parameter. function Get (Name : in String) return String; -- Initalize the list of gateways from the configuration file. procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector); end Druss.Config;
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Gateways; package Druss.Config is -- Initialize the configuration. procedure Initialize (Path : in String); -- Get the configuration parameter. function Get (Name : in String) return String; -- Initalize the list of gateways from the configuration file. procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (List : in Druss.Gateways.Gateway_Vector); end Druss.Config;
Declare the Save_Gateways procedure
Declare the Save_Gateways procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
043ea3b1830cd579b8ff9ddc4046f4b0fc8a869d
src/ado-queries.adb
src/ado-queries.adb
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries.Loaders; package body ADO.Queries is -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. -- ------------------------------ procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := False; end Set_Query; -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. -- ------------------------------ procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := True; end Set_Count_Query; procedure Set_Query (Into : in out Context; Name : in String) is begin Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name); end Set_Query; -- ------------------------------ -- Set the query to execute as SQL statement. -- ------------------------------ procedure Set_SQL (Into : in out Context; SQL : in String) is begin ADO.SQL.Clear (Into.SQL); ADO.SQL.Append (Into.SQL, SQL); end Set_SQL; -- ------------------------------ -- Set the limit for the SQL query. -- ------------------------------ procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural) is begin Into.First := First; Into.Last := Last; end Set_Limit; -- ------------------------------ -- Get the first row index. -- ------------------------------ function Get_First_Row_Index (From : in Context) return Natural is begin return From.First; end Get_First_Row_Index; -- ------------------------------ -- Get the last row index. -- ------------------------------ function Get_Last_Row_Index (From : in Context) return Natural is begin return From.Last; end Get_Last_Row_Index; -- ------------------------------ -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. -- ------------------------------ function Get_Max_Row_Count (From : in Context) return Natural is begin return From.Max_Row_Count; end Get_Max_Row_Count; -- ------------------------------ -- Get the SQL query that correspond to the query context. -- ------------------------------ function Get_SQL (From : in Context; Manager : in Query_Manager_Access) return String is begin if From.Query_Def = null then return ADO.SQL.To_String (From.SQL); else return Get_SQL (From.Query_Def, Manager, From.Is_Count); end if; end Get_SQL; -- ------------------------------ -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none -- ------------------------------ function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access is Query : Query_Definition_Access := File.File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; return null; end Find_Query; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager_Access; Use_Count : in Boolean) return String is Query : Query_Info_Ref.Ref; begin ADO.Queries.Loaders.Read_Query (Manager.all, From); Query := Manager.Queries (From.Query).Get; if Query.Is_Null then return ""; end if; if Use_Count then if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then return To_String (Query.Value.Count_Query (Manager.Driver).SQL); else return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL); end if; elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then return To_String (Query.Value.Main_Query (Manager.Driver).SQL); else return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL); end if; end Get_SQL; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries.Loaders; package body ADO.Queries is -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. -- ------------------------------ procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := False; end Set_Query; -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. -- ------------------------------ procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := True; end Set_Count_Query; procedure Set_Query (Into : in out Context; Name : in String) is begin Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name); end Set_Query; -- ------------------------------ -- Set the query to execute as SQL statement. -- ------------------------------ procedure Set_SQL (Into : in out Context; SQL : in String) is begin ADO.SQL.Clear (Into.SQL); ADO.SQL.Append (Into.SQL, SQL); end Set_SQL; -- ------------------------------ -- Set the limit for the SQL query. -- ------------------------------ procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural) is begin Into.First := First; Into.Last := Last; end Set_Limit; -- ------------------------------ -- Get the first row index. -- ------------------------------ function Get_First_Row_Index (From : in Context) return Natural is begin return From.First; end Get_First_Row_Index; -- ------------------------------ -- Get the last row index. -- ------------------------------ function Get_Last_Row_Index (From : in Context) return Natural is begin return From.Last; end Get_Last_Row_Index; -- ------------------------------ -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. -- ------------------------------ function Get_Max_Row_Count (From : in Context) return Natural is begin return From.Max_Row_Count; end Get_Max_Row_Count; -- ------------------------------ -- Get the SQL query that correspond to the query context. -- ------------------------------ function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String is begin if From.Query_Def = null then return ADO.SQL.To_String (From.SQL); else return Get_SQL (From.Query_Def, Manager, From.Is_Count); end if; end Get_SQL; -- ------------------------------ -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none -- ------------------------------ function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access is Query : Query_Definition_Access := File.File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; return null; end Find_Query; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String is Query : Query_Info_Ref.Ref; begin ADO.Queries.Loaders.Read_Query (Manager, From); Query := Manager.Queries (From.Query).Get; if Query.Is_Null then return ""; end if; if Use_Count then if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then return To_String (Query.Value.Count_Query (Manager.Driver).SQL); else return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL); end if; elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then return To_String (Query.Value.Main_Query (Manager.Driver).SQL); else return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL); end if; end Get_SQL; overriding procedure Finalize (Manager : in out Query_Manager) is begin null; end Finalize; end ADO.Queries;
Replace Query_Manager_Access by Query_Manager as parameter Implement stub for Finalize procedure
Replace Query_Manager_Access by Query_Manager as parameter Implement stub for Finalize procedure
Ada
apache-2.0
stcarrez/ada-ado
ef84344164524be035f53fa85ac219cf7be47fcf
src/babel-files.ads
src/babel-files.ads
----------------------------------------------------------------------- -- 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.Calendar; with Ada.Strings.Unbounded; with Util.Encoders.SHA1; with ADO; package Babel.Files is NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER; subtype File_Identifier is ADO.Identifier; subtype Directory_Identifier is ADO.Identifier; subtype File_Size is Long_Long_Integer; type File_Mode is mod 2**16; type Uid_Type is mod 2**16; type Gid_Type is mod 2**16; type File_Type is private; type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; type Directory_Type is private; type Directory_Type_Array is array (Positive range <>) of Directory_Type; type Directory_Type_Array_Access is access all Directory_Type_Array; NO_DIRECTORY : constant Directory_Type; NO_FILE : constant File_Type; type Status_Type is mod 2**16; -- The file was modified. FILE_MODIFIED : constant Status_Type := 16#0001#; -- There was some error while processing this file. FILE_ERROR : constant Status_Type := 16#8000#; -- The SHA1 signature for the file is known and valid. FILE_HAS_SHA1 : constant Status_Type := 16#0002#; -- Allocate a File_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return File_Type; -- Allocate a Directory_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type; type File (Len : Positive) is record Id : File_Identifier := NO_IDENTIFIER; Size : File_Size := 0; Dir : Directory_Type := NO_DIRECTORY; Mode : File_Mode := 8#644#; User : Uid_Type := 0; Group : Gid_Type := 0; Status : Status_Type := 0; Date : Ada.Calendar.Time; SHA1 : Util.Encoders.SHA1.Hash_Array; Name : aliased String (1 .. Len); end record; -- Return true if the file was modified and need a backup. function Is_Modified (Element : in File_Type) return Boolean; -- Set the file as modified. procedure Set_Modified (Element : in File_Type); -- 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); -- 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); -- Return the path for the file. function Get_Path (Element : in File_Type) return String; -- Return the path for the directory. function Get_Path (Element : in Directory_Type) return String; -- Return the SHA1 signature computed for the file. function Get_SHA1 (Element : in File_Type) return String; type File_Container is limited interface; -- Add the file with the given name in the container. procedure Add_File (Into : in out File_Container; Path : in String; Element : in File) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Path : in String; Name : in String) is abstract; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in File_Container; Name : in String) return File_Type is abstract; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in File_Container; Name : in String) return Directory_Type is abstract; private type Directory (Len : Positive) is record Id : Directory_Identifier := NO_IDENTIFIER; Parent : Directory_Type; Mode : File_Mode := 8#755#; User : Uid_Type := 0; Group : Gid_Type := 0; Files : File_Type_Array_Access; Children : Directory_Type_Array_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Name : aliased String (1 .. Len); end record; type File_Type is access all File; type Directory_Type is access all Directory; NO_DIRECTORY : constant Directory_Type := null; NO_FILE : constant File_Type := null; 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.Calendar; with Ada.Strings.Unbounded; with Util.Encoders.SHA1; with ADO; package Babel.Files is NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER; subtype File_Identifier is ADO.Identifier; subtype Directory_Identifier is ADO.Identifier; subtype File_Size is Long_Long_Integer; type File_Mode is mod 2**16; type Uid_Type is mod 2**16; type Gid_Type is mod 2**16; type File_Type is private; type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; type Directory_Type is private; type Directory_Type_Array is array (Positive range <>) of Directory_Type; type Directory_Type_Array_Access is access all Directory_Type_Array; NO_DIRECTORY : constant Directory_Type; NO_FILE : constant File_Type; type Status_Type is mod 2**16; -- The file was modified. FILE_MODIFIED : constant Status_Type := 16#0001#; -- There was some error while processing this file. FILE_ERROR : constant Status_Type := 16#8000#; -- The SHA1 signature for the file is known and valid. FILE_HAS_SHA1 : constant Status_Type := 16#0002#; -- Allocate a File_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return File_Type; -- Allocate a Directory_Type entry with the given name for the directory. function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type; type File (Len : Positive) is record Id : File_Identifier := NO_IDENTIFIER; Size : File_Size := 0; Dir : Directory_Type := NO_DIRECTORY; Mode : File_Mode := 8#644#; User : Uid_Type := 0; Group : Gid_Type := 0; Status : Status_Type := 0; Date : Ada.Calendar.Time; SHA1 : Util.Encoders.SHA1.Hash_Array; Name : aliased String (1 .. Len); end record; -- Return true if the file was modified and need a backup. function Is_Modified (Element : in File_Type) return Boolean; -- Set the file as modified. procedure Set_Modified (Element : in File_Type); -- 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); -- 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); -- Return the path for the file. function Get_Path (Element : in File_Type) return String; -- Return the path for the directory. function Get_Path (Element : in Directory_Type) return String; -- Return the SHA1 signature computed for the file. function Get_SHA1 (Element : in File_Type) return String; type File_Container is limited interface; -- Add the file with the given name in the container. procedure Add_File (Into : in out File_Container; Path : in String; Element : in File) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Path : in String; Name : in String) is abstract; -- Create a new file instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return File_Type is abstract; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in File_Container; Name : in String) return File_Type is abstract; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in File_Container; Name : in String) return Directory_Type is abstract; private type Directory (Len : Positive) is record Id : Directory_Identifier := NO_IDENTIFIER; Parent : Directory_Type; Mode : File_Mode := 8#755#; User : Uid_Type := 0; Group : Gid_Type := 0; Files : File_Type_Array_Access; Children : Directory_Type_Array_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Name : aliased String (1 .. Len); end record; type File_Type is access all File; type Directory_Type is access all Directory; NO_DIRECTORY : constant Directory_Type := null; NO_FILE : constant File_Type := null; end Babel.Files;
Add a Create function in the File_Container to create a file instance
Add a Create function in the File_Container to create a file instance
Ada
apache-2.0
stcarrez/babel
11c676bf1af93a0d31fac69950f62649f6bcf429
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 -- 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;
----------------------------------------------------------------------- -- 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 new Ada.Finalization.Limited_Controlled with 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; -- Release the target process instance. overriding procedure Finalize (Target : in out Target_Process_Type); 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; -- Release the storage used by the target object. overriding procedure Finalize (Target : in out Target_Type); end MAT.Targets;
Declare the Finalize procedure
Declare the Finalize procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e7937362e0445d10ac7a7e1c957aae6fe8f6ea09
src/sys/encoders/util-encoders-hmac-sha256.adb
src/sys/encoders/util-encoders-hmac-sha256.adb
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base16; with Util.Encoders.Base64; package body Util.Encoders.HMAC.SHA256 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA256.Hash_Array; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data array with the key and return the HMAC-SHA256 code in the result. -- ------------------------------ procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array) is Ctx : Context; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); end Sign; procedure Sign (Key : in Secret_Key; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array) is begin Sign (Key.Secret, Data, Result); end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest is Ctx : Context; Result : Util.Encoders.SHA256.Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA256.Base64_Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish_Base64 (Ctx, Result, URL); return Result; end Sign_Base64; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in String) is Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length); for Buf'Address use Key'Address; pragma Import (Ada, Buf); begin Set_Key (E, Buf); end Set_Key; IPAD : constant Ada.Streams.Stream_Element := 16#36#; OPAD : constant Ada.Streams.Stream_Element := 16#5c#; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array) is begin -- Reduce the key if Key'Length > 64 then Util.Encoders.SHA256.Update (E.SHA, Key); Util.Encoders.SHA256.Finish (E.SHA, E.Key (0 .. 31)); E.Key_Len := 31; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA256 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := IPAD xor E.Key (I); end loop; for I in E.Key_Len + 1 .. 63 loop Block (I) := IPAD; end loop; Util.Encoders.SHA256.Update (E.SHA, Block); end; end Set_Key; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in String) is begin Util.Encoders.SHA256.Update (E.SHA, S); end Update; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) is begin Util.Encoders.SHA256.Update (E.SHA, S); end Update; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Hash_Array) is begin Util.Encoders.SHA256.Finish (E.SHA, Hash); -- Hash the key in the SHA256 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := OPAD xor E.Key (I); end loop; if E.Key_Len < 63 then for I in E.Key_Len + 1 .. 63 loop Block (I) := OPAD; end loop; end if; Util.Encoders.SHA256.Update (E.SHA, Block); end; Util.Encoders.SHA256.Update (E.SHA, Hash); Util.Encoders.SHA256.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Digest) is H : Util.Encoders.SHA256.Hash_Array; B : Util.Encoders.Base16.Encoder; begin Finish (E, H); B.Convert (H, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA256.Base64_Digest; URL : in Boolean := False) is H : Util.Encoders.SHA256.Hash_Array; B : Util.Encoders.Base64.Encoder; begin Finish (E, H); B.Set_URL_Mode (URL); B.Convert (H, Hash); end Finish_Base64; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA256;
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA256 authentication code -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base16; with Util.Encoders.Base64; package body Util.Encoders.HMAC.SHA256 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA256.Hash_Array; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data array with the key and return the HMAC-SHA256 code in the result. -- ------------------------------ procedure Sign (Key : in Ada.Streams.Stream_Element_Array; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array) is Ctx : Context; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); end Sign; procedure Sign (Key : in Secret_Key; Data : in Ada.Streams.Stream_Element_Array; Result : out Util.Encoders.SHA256.Hash_Array) is begin Sign (Key.Secret, Data, Result); end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA256.Digest is Ctx : Context; Result : Util.Encoders.SHA256.Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); return Result; end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA256 code as base64 string. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ function Sign_Base64 (Key : in String; Data : in String; URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA256.Base64_Digest; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish_Base64 (Ctx, Result, URL); return Result; end Sign_Base64; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in String) is Buf : Ada.Streams.Stream_Element_Array (1 .. Key'Length); for Buf'Address use Key'Address; pragma Import (Ada, Buf); begin Set_Key (E, Buf); end Set_Key; IPAD : constant Ada.Streams.Stream_Element := 16#36#; OPAD : constant Ada.Streams.Stream_Element := 16#5c#; -- ------------------------------ -- Set the hmac private key. The key must be set before calling any <b>Update</b> -- procedure. -- ------------------------------ procedure Set_Key (E : in out Context; Key : in Ada.Streams.Stream_Element_Array) is begin -- Reduce the key if Key'Length > 64 then Util.Encoders.SHA256.Update (E.SHA, Key); Util.Encoders.SHA256.Finish (E.SHA, E.Key (0 .. 31)); E.Key_Len := 31; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA256 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := IPAD xor E.Key (I); end loop; for I in E.Key_Len + 1 .. 63 loop Block (I) := IPAD; end loop; Util.Encoders.SHA256.Update (E.SHA, Block); end; end Set_Key; procedure Set_Key (E : in out Context; Key : in Secret_Key) is begin Set_Key (E, Key.Secret); end Set_Key; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in String) is begin Util.Encoders.SHA256.Update (E.SHA, S); end Update; -- ------------------------------ -- Update the hash with the string. -- ------------------------------ procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array) is begin Util.Encoders.SHA256.Update (E.SHA, S); end Update; -- ------------------------------ -- Update the hash with the secret key. -- ------------------------------ procedure Update (E : in out Context; S : in Secret_Key) is begin Update (E, S.Secret); end Update; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Hash_Array) is begin Util.Encoders.SHA256.Finish (E.SHA, Hash); -- Hash the key in the SHA256 context. declare Block : Ada.Streams.Stream_Element_Array (0 .. 63); begin for I in 0 .. E.Key_Len loop Block (I) := OPAD xor E.Key (I); end loop; if E.Key_Len < 63 then for I in E.Key_Len + 1 .. 63 loop Block (I) := OPAD; end loop; end if; Util.Encoders.SHA256.Update (E.SHA, Block); end; Util.Encoders.SHA256.Update (E.SHA, Hash); Util.Encoders.SHA256.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>. -- ------------------------------ procedure Finish (E : in out Context; Hash : out Util.Encoders.SHA256.Digest) is H : Util.Encoders.SHA256.Hash_Array; B : Util.Encoders.Base16.Encoder; begin Finish (E, H); B.Convert (H, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA256 with the private key and the data collected by -- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>. -- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64. -- ------------------------------ procedure Finish_Base64 (E : in out Context; Hash : out Util.Encoders.SHA256.Base64_Digest; URL : in Boolean := False) is H : Util.Encoders.SHA256.Hash_Array; B : Util.Encoders.Base64.Encoder; begin Finish (E, H); B.Set_URL_Mode (URL); B.Convert (H, Hash); end Finish_Base64; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA256;
Implement Set_Key and Update procedures
Implement Set_Key and Update procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bb601edcbbf7c2243740f8792f13919896c1da56
orka_glfw/src/orka-windows-glfw.ads
orka_glfw/src/orka-windows-glfw.ads
-- 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. private with Ada.Finalization; private with GL.Objects.Vertex_Arrays; private with GL.Types; private with Orka.Inputs.Pointers; private with Glfw.Windows; private with Glfw.Input.Keys; private with Glfw.Input.Mouse; with Orka.Contexts; package Orka.Windows.GLFW is type GLFW_Context is limited new Contexts.Surface_Context with private; overriding function Create_Context (Version : Contexts.Context_Version; Flags : Contexts.Context_Flags := (others => False)) return GLFW_Context; type GLFW_Window is limited new Window with private; overriding procedure Set_Title (Object : in out GLFW_Window; Value : String); overriding function Should_Close (Object : GLFW_Window) return Boolean; 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 with Pre => Context in GLFW_Context'Class; private type GLFW_Context is limited new Ada.Finalization.Limited_Controlled and Contexts.Surface_Context with record Version : Contexts.Context_Version; Flags : Contexts.Context_Flags; Features : Contexts.Feature_Array := (others => False); end record; overriding procedure Finalize (Object : in out GLFW_Context); overriding procedure Enable (Object : in out GLFW_Context; Subject : Contexts.Feature); overriding function Enabled (Object : GLFW_Context; Subject : Contexts.Feature) return Boolean; overriding function Version (Object : GLFW_Context) return Contexts.Context_Version; overriding function Flags (Object : GLFW_Context) return Contexts.Context_Flags; overriding function Is_Current (Object : GLFW_Context; Kind : Orka.Contexts.Task_Kind) return Boolean; overriding procedure Make_Current (Object : GLFW_Context); overriding procedure Make_Current (Object : GLFW_Context; Window : in out Orka.Windows.Window'Class); overriding procedure Make_Not_Current (Object : GLFW_Context); type GLFW_Window is limited new Standard.Glfw.Windows.Window and Window with record Input : Inputs.Pointers.Pointer_Input_Ptr; Finalized : Boolean; Vertex_Array : GL.Objects.Vertex_Arrays.Vertex_Array_Object; Position_X : GL.Types.Double := 0.0; Position_Y : GL.Types.Double := 0.0; Scroll_X : GL.Types.Double := 0.0; Scroll_Y : GL.Types.Double := 0.0; Width, Height : Positive; -- Needed to workaround a GLFW bug Got_Locked, Last_Locked : Boolean := False; end record; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointers.Pointer_Input_Ptr; overriding function Width (Object : GLFW_Window) return Positive; overriding function Height (Object : GLFW_Window) return Positive; overriding procedure Close (Object : in out GLFW_Window); overriding procedure Process_Input (Object : in out GLFW_Window); overriding procedure Swap_Buffers (Object : in out GLFW_Window); overriding procedure Set_Vertical_Sync (Object : in out GLFW_Window; Enable : Boolean); overriding procedure Finalize (Object : in out GLFW_Window); overriding procedure Close_Requested (Object : not null access GLFW_Window); 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); overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate); overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset); 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); overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural); 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. private with Ada.Finalization; private with GL.Objects.Vertex_Arrays; private with GL.Types; private with Orka.Inputs.Pointers; private with Glfw.Windows; private with Glfw.Input.Keys; private with Glfw.Input.Mouse; with Orka.Contexts; package Orka.Windows.GLFW is pragma Preelaborate; type GLFW_Context is limited new Contexts.Surface_Context with private; overriding function Create_Context (Version : Contexts.Context_Version; Flags : Contexts.Context_Flags := (others => False)) return GLFW_Context; type GLFW_Window is limited new Window with private; overriding procedure Set_Title (Object : in out GLFW_Window; Value : String); overriding function Should_Close (Object : GLFW_Window) return Boolean; 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 with Pre => Context in GLFW_Context'Class; private type GLFW_Context is limited new Ada.Finalization.Limited_Controlled and Contexts.Surface_Context with record Version : Contexts.Context_Version; Flags : Contexts.Context_Flags; Features : Contexts.Feature_Array := (others => False); end record; overriding procedure Finalize (Object : in out GLFW_Context); overriding procedure Enable (Object : in out GLFW_Context; Subject : Contexts.Feature); overriding function Enabled (Object : GLFW_Context; Subject : Contexts.Feature) return Boolean; overriding function Version (Object : GLFW_Context) return Contexts.Context_Version; overriding function Flags (Object : GLFW_Context) return Contexts.Context_Flags; overriding function Is_Current (Object : GLFW_Context; Kind : Orka.Contexts.Task_Kind) return Boolean; overriding procedure Make_Current (Object : GLFW_Context); overriding procedure Make_Current (Object : GLFW_Context; Window : in out Orka.Windows.Window'Class); overriding procedure Make_Not_Current (Object : GLFW_Context); type GLFW_Window is limited new Standard.Glfw.Windows.Window and Window with record Input : Inputs.Pointers.Pointer_Input_Ptr; Finalized : Boolean; Vertex_Array : GL.Objects.Vertex_Arrays.Vertex_Array_Object; Position_X : GL.Types.Double := 0.0; Position_Y : GL.Types.Double := 0.0; Scroll_X : GL.Types.Double := 0.0; Scroll_Y : GL.Types.Double := 0.0; Width, Height : Positive; -- Needed to workaround a GLFW bug Got_Locked, Last_Locked : Boolean := False; end record; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointers.Pointer_Input_Ptr; overriding function Width (Object : GLFW_Window) return Positive; overriding function Height (Object : GLFW_Window) return Positive; overriding procedure Close (Object : in out GLFW_Window); overriding procedure Process_Input (Object : in out GLFW_Window); overriding procedure Swap_Buffers (Object : in out GLFW_Window); overriding procedure Set_Vertical_Sync (Object : in out GLFW_Window; Enable : Boolean); overriding procedure Finalize (Object : in out GLFW_Window); overriding procedure Close_Requested (Object : not null access GLFW_Window); 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); overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate); overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset); 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); overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural); end Orka.Windows.GLFW;
Make package Orka.Windows.GLFW preelaborated
glfw: Make package Orka.Windows.GLFW preelaborated Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
a5264cc630fdf71c33caccd3304d4a174b36258c
tools/druss-config.adb
tools/druss-config.adb
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Environment_Variables; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Files; with Util.Properties; package body Druss.Config is Cfg : Util.Properties.Manager; Cfg_Path : Ada.Strings.Unbounded.Unbounded_String; -- ------------------------------ -- Initialize the configuration. -- ------------------------------ procedure Initialize (Path : in String) is Home : constant String := Ada.Environment_Variables.Value ("HOME"); Def_Path : constant String := Util.Files.Compose (Home, ".config/druss/druss.properties"); begin if Path'Length > 0 and then Ada.Directories.Exists (Path) then Cfg.Load_Properties (Path); Cfg_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); elsif Ada.Directories.Exists (Def_Path) then Cfg.Load_Properties (Def_Path); Cfg_Path := Ada.Strings.Unbounded.To_Unbounded_String (Def_Path); end if; end Initialize; -- ------------------------------ -- Get the configuration parameter. -- ------------------------------ function Get (Name : in String) return String is begin return Cfg.Get (Name); end Get; -- ------------------------------ -- Initalize the list of gateways from the configuration file. -- ------------------------------ procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector) is begin Druss.Gateways.Initialize (Cfg, List); end Get_Gateways; end Druss.Config;
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Environment_Variables; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Files; with Util.Properties; package body Druss.Config is Cfg : Util.Properties.Manager; Cfg_Path : Ada.Strings.Unbounded.Unbounded_String; -- ------------------------------ -- Initialize the configuration. -- ------------------------------ procedure Initialize (Path : in String) is Home : constant String := Ada.Environment_Variables.Value ("HOME"); Def_Path : constant String := Util.Files.Compose (Home, ".config/druss/druss.properties"); begin if Path'Length > 0 and then Ada.Directories.Exists (Path) then Cfg.Load_Properties (Path); Cfg_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); elsif Ada.Directories.Exists (Def_Path) then Cfg.Load_Properties (Def_Path); Cfg_Path := Ada.Strings.Unbounded.To_Unbounded_String (Def_Path); end if; end Initialize; procedure Save is Path : constant String := Ada.Strings.Unbounded.To_String (Cfg_Path); begin if not Ada.Directories.Exists (Path) then Ada.Directories.Create_Path (Ada.Directories.Containing_Directory (Path)); end if; Cfg.Save_Properties (Path); end Save; -- ------------------------------ -- Get the configuration parameter. -- ------------------------------ function Get (Name : in String) return String is begin return Cfg.Get (Name); end Get; -- ------------------------------ -- Initalize the list of gateways from the configuration file. -- ------------------------------ procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector) is begin Druss.Gateways.Initialize (Cfg, List); end Get_Gateways; -- ------------------------------ -- Save the list of gateways. -- ------------------------------ procedure Save_Gateways (List : in Druss.Gateways.Gateway_Vector) is begin Druss.Gateways.Save_Gateways (Cfg, List); Save; end Save_Gateways; end Druss.Config;
Implement the Save_Gateways procedure
Implement the Save_Gateways procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
882f8515f98f0dd3360c55050b26f8cac5afe7c4
src/asf-components-html-selects.adb
src/asf-components-html-selects.adb
----------------------------------------------------------------------- -- html-selects -- ASF HTML UISelectOne and UISelectMany components -- Copyright (C) 2011, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Utils; package body ASF.Components.Html.Selects is -- ------------------------------ -- UISelectItem Component -- ------------------------------ ITEM_LABEL_NAME : constant String := "itemLabel"; ITEM_VALUE_NAME : constant String := "itemValue"; ITEM_DESCRIPTION_NAME : constant String := "itemDescription"; ITEM_DISABLED_NAME : constant String := "itemDisabled"; SELECT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- UISelectBoolean Component -- ------------------------------ -- Render the checkbox element. overriding procedure Render_Input (UI : in UISelectBoolean; Context : in out Faces_Context'Class; Write_Id : in Boolean := True) is use ASF.Components.Html.Forms; Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UIInput'Class (UI).Get_Value; begin Writer.Start_Element ("input"); Writer.Write_Attribute (Name => "type", Value => "checkbox"); UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer, Write_Id); Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id); if not EL.Objects.Is_Null (Value) and then EL.Objects.To_Boolean (Value) then Writer.Write_Attribute (Name => "checked", Value => "true"); end if; Writer.End_Element ("input"); end Render_Input; -- ------------------------------ -- Convert the string into a value. If a converter is specified on the component, -- use it to convert the value. Make sure the result is a boolean. -- ------------------------------ overriding function Convert_Value (UI : in UISelectBoolean; Value : in String; Context : in Faces_Context'Class) return EL.Objects.Object is use type EL.Objects.Data_Type; Result : constant EL.Objects.Object := Forms.UIInput (UI).Convert_Value (Value, Context); begin case EL.Objects.Get_Type (Result) is when EL.Objects.TYPE_BOOLEAN => return Result; when EL.Objects.TYPE_INTEGER => return EL.Objects.To_Object (EL.Objects.To_Boolean (Result)); when others => if Value = "on" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end case; end Convert_Value; -- ------------------------------ -- Iterator over the Select_Item elements -- ------------------------------ -- ------------------------------ -- Get an iterator to scan the component children. -- ------------------------------ procedure First (UI : in UISelectOne'Class; Context : in Faces_Context'Class; Iterator : out Cursor) is begin Iterator.Component := UI.First; Iterator.Pos := 0; Iterator.Last := 0; while ASF.Components.Base.Has_Element (Iterator.Component) loop Iterator.Current := ASF.Components.Base.Element (Iterator.Component); if Iterator.Current.all in UISelectItem'Class then return; end if; if Iterator.Current.all in UISelectItems'Class then Iterator.List := UISelectItems'Class (Iterator.Current.all) .Get_Select_Item_List (Context); Iterator.Last := Iterator.List.Length; Iterator.Pos := 1; if Iterator.Last > 0 then return; end if; end if; ASF.Components.Base.Next (Iterator.Component); end loop; Iterator.Pos := 0; Iterator.Current := null; end First; -- ------------------------------ -- Returns True if the iterator points to a valid child. -- ------------------------------ function Has_Element (Pos : in Cursor) return Boolean is use type ASF.Components.Base.UIComponent_Access; begin if Pos.Pos > 0 and Pos.Pos <= Pos.Last then return True; else return Pos.Current /= null; end if; end Has_Element; -- ------------------------------ -- Get the child component pointed to by the iterator. -- ------------------------------ function Element (Pos : in Cursor; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is begin if Pos.Pos > 0 and Pos.Pos <= Pos.Last then return Pos.List.Get_Select_Item (Pos.Pos); else return UISelectItem'Class (Pos.Current.all).Get_Select_Item (Context); end if; end Element; -- ------------------------------ -- Move to the next child. -- ------------------------------ procedure Next (Pos : in out Cursor; Context : in Faces_Context'Class) is begin if Pos.Pos > 0 and Pos.Pos < Pos.Last then Pos.Pos := Pos.Pos + 1; else Pos.Pos := 0; loop Pos.Current := null; ASF.Components.Base.Next (Pos.Component); exit when not ASF.Components.Base.Has_Element (Pos.Component); Pos.Current := ASF.Components.Base.Element (Pos.Component); exit when Pos.Current.all in UISelectItem'Class; if Pos.Current.all in UISelectItems'Class then Pos.List := UISelectItems'Class (Pos.Current.all).Get_Select_Item_List (Context); Pos.Last := Pos.List.Length; Pos.Pos := 1; exit when Pos.Last > 0; Pos.Pos := 0; end if; end loop; end if; end Next; -- ------------------------------ -- Get the <b>Select_Item</b> represented by the component. -- ------------------------------ function Get_Select_Item (From : in UISelectItem; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is use Util.Beans.Objects; Val : constant Object := From.Get_Attribute (Name => VALUE_NAME, Context => Context); begin if not Is_Null (Val) then return ASF.Models.Selects.To_Select_Item (Val); end if; declare Label : constant Object := From.Get_Attribute (Name => ITEM_LABEL_NAME, Context => Context); Value : constant Object := From.Get_Attribute (Name => ITEM_VALUE_NAME, Context => Context); Description : constant Object := From.Get_Attribute (Name => ITEM_DESCRIPTION_NAME, Context => Context); Disabled : constant Boolean := From.Get_Attribute (Name => ITEM_DISABLED_NAME, Context => Context); begin if Is_Null (Label) then return ASF.Models.Selects.Create_Select_Item (Value, Value, Description, Disabled); else return ASF.Models.Selects.Create_Select_Item (Label, Value, Description, Disabled); end if; end; end Get_Select_Item; -- ------------------------------ -- UISelectItems Component -- ------------------------------ -- ------------------------------ -- Get the <b>Select_Item</b> represented by the component. -- ------------------------------ function Get_Select_Item_List (From : in UISelectItems; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item_List is use Util.Beans.Objects; Value : constant Object := From.Get_Attribute (Name => VALUE_NAME, Context => Context); begin return ASF.Models.Selects.To_Select_Item_List (Value); end Get_Select_Item_List; -- ------------------------------ -- SelectOne Component -- ------------------------------ -- ------------------------------ -- Render the <b>select</b> element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UISelectOne; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UISelectOne'Class (UI).Render_Select (Context); end if; end Encode_Begin; -- ------------------------------ -- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if -- the component is rendered. -- ------------------------------ procedure Render_Select (UI : in UISelectOne; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value; begin Writer.Start_Element ("select"); Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id); UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer); UISelectOne'Class (UI).Render_Options (Value, Context); Writer.End_Element ("select"); end Render_Select; -- ------------------------------ -- Renders the <b>option</b> element. This is called by <b>Render_Select</b> to -- generate the component options. -- ------------------------------ procedure Render_Options (UI : in UISelectOne; Value : in Util.Beans.Objects.Object; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value); Iter : Cursor; begin UI.First (Context, Iter); while Has_Element (Iter) loop declare Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context); Item_Value : constant Wide_Wide_String := Item.Get_Value; begin Writer.Start_Element ("option"); Writer.Write_Wide_Attribute ("value", Item_Value); if Item_Value = Selected then Writer.Write_Attribute ("selected", "selected"); end if; if Item.Is_Escaped then Writer.Write_Wide_Text (Item.Get_Label); else Writer.Write_Wide_Text (Item.Get_Label); end if; Writer.End_Element ("option"); Next (Iter, Context); end; end loop; end Render_Options; -- ------------------------------ -- Returns True if the radio options must be rendered vertically. -- ------------------------------ function Is_Vertical (UI : in UISelectOneRadio; Context : in Faces_Context'Class) return Boolean is Dir : constant String := UI.Get_Attribute (Context => Context, Name => "layout", Default => ""); begin return Dir = "pageDirection"; end Is_Vertical; -- ------------------------------ -- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if -- the component is rendered. -- ------------------------------ overriding procedure Render_Select (UI : in UISelectOneRadio; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value; Vertical : constant Boolean := UI.Is_Vertical (Context); Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value); Iter : Cursor; Id : constant String := To_String (UI.Get_Client_Id); N : Natural := 0; Disabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context, Name => "disabledClass"); Enabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context, Name => "enabledClass"); begin Writer.Start_Element ("table"); UI.Render_Attributes (Context, Writer); if not Vertical then Writer.Start_Element ("tr"); end if; UI.First (Context, Iter); while Has_Element (Iter) loop declare Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context); Item_Value : constant Wide_Wide_String := Item.Get_Value; begin if Vertical then Writer.Start_Element ("tr"); end if; Writer.Start_Element ("td"); -- Render the input radio checkbox. Writer.Start_Element ("input"); Writer.Write_Attribute ("type", "radio"); if Item.Is_Disabled then Writer.Write_Attribute ("disabled", "disabled"); end if; Writer.Write_Attribute ("id", Id & "_" & Util.Strings.Image (N)); Writer.Write_Wide_Attribute ("value", Item_Value); if Item_Value = Selected then Writer.Write_Attribute ("checked", "checked"); end if; Writer.End_Element ("input"); -- Render the label associated with the checkbox. Writer.Start_Element ("label"); if Item.Is_Disabled then if not Util.Beans.Objects.Is_Null (Disabled_Class) then Writer.Write_Attribute ("class", Disabled_Class); end if; else if not Util.Beans.Objects.Is_Null (Enabled_Class) then Writer.Write_Attribute ("class", Enabled_Class); end if; end if; Writer.Write_Attribute ("for", Id & "_" & Util.Strings.Image (N)); if Item.Is_Escaped then Writer.Write_Wide_Text (Item.Get_Label); else Writer.Write_Wide_Text (Item.Get_Label); end if; Writer.End_Element ("label"); Writer.End_Element ("td"); if Vertical then Writer.End_Element ("tr"); end if; Next (Iter, Context); N := N + 1; end; end loop; if not Vertical then Writer.End_Element ("tr"); end if; Writer.End_Element ("table"); end Render_Select; begin ASF.Utils.Set_Text_Attributes (SELECT_ATTRIBUTE_NAMES); ASF.Utils.Set_Interactive_Attributes (SELECT_ATTRIBUTE_NAMES); end ASF.Components.Html.Selects;
----------------------------------------------------------------------- -- html-selects -- ASF HTML UISelectOne and UISelectMany components -- Copyright (C) 2011, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Utils; package body ASF.Components.Html.Selects is -- ------------------------------ -- UISelectItem Component -- ------------------------------ ITEM_LABEL_NAME : constant String := "itemLabel"; ITEM_VALUE_NAME : constant String := "itemValue"; ITEM_DESCRIPTION_NAME : constant String := "itemDescription"; ITEM_DISABLED_NAME : constant String := "itemDisabled"; SELECT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- UISelectBoolean Component -- ------------------------------ -- Render the checkbox element. overriding procedure Render_Input (UI : in UISelectBoolean; Context : in out Faces_Context'Class; Write_Id : in Boolean := True) is use ASF.Components.Html.Forms; Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UIInput'Class (UI).Get_Value; begin Writer.Start_Element ("input"); Writer.Write_Attribute (Name => "type", Value => "checkbox"); UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer, Write_Id); Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id); if not EL.Objects.Is_Null (Value) and then EL.Objects.To_Boolean (Value) then Writer.Write_Attribute (Name => "checked", Value => "true"); end if; Writer.End_Element ("input"); end Render_Input; -- ------------------------------ -- Convert the string into a value. If a converter is specified on the component, -- use it to convert the value. Make sure the result is a boolean. -- ------------------------------ overriding function Convert_Value (UI : in UISelectBoolean; Value : in String; Context : in Faces_Context'Class) return EL.Objects.Object is use type EL.Objects.Data_Type; Result : constant EL.Objects.Object := Forms.UIInput (UI).Convert_Value (Value, Context); begin case EL.Objects.Get_Type (Result) is when EL.Objects.TYPE_BOOLEAN => return Result; when EL.Objects.TYPE_INTEGER => return EL.Objects.To_Object (EL.Objects.To_Boolean (Result)); when others => if Value = "on" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end case; end Convert_Value; -- ------------------------------ -- Iterator over the Select_Item elements -- ------------------------------ -- ------------------------------ -- Get an iterator to scan the component children. -- ------------------------------ procedure First (UI : in UISelectOne'Class; Context : in Faces_Context'Class; Iterator : out Cursor) is begin Iterator.Component := UI.First; Iterator.Pos := 0; Iterator.Last := 0; while ASF.Components.Base.Has_Element (Iterator.Component) loop Iterator.Current := ASF.Components.Base.Element (Iterator.Component); if Iterator.Current.all in UISelectItem'Class then return; end if; if Iterator.Current.all in UISelectItems'Class then Iterator.List := UISelectItems'Class (Iterator.Current.all) .Get_Select_Item_List (Context); Iterator.Last := Iterator.List.Length; Iterator.Pos := 1; if Iterator.Last > 0 then return; end if; end if; ASF.Components.Base.Next (Iterator.Component); end loop; Iterator.Pos := 0; Iterator.Current := null; end First; -- ------------------------------ -- Returns True if the iterator points to a valid child. -- ------------------------------ function Has_Element (Pos : in Cursor) return Boolean is use type ASF.Components.Base.UIComponent_Access; begin if Pos.Pos > 0 and Pos.Pos <= Pos.Last then return True; else return Pos.Current /= null; end if; end Has_Element; -- ------------------------------ -- Get the child component pointed to by the iterator. -- ------------------------------ function Element (Pos : in Cursor; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is begin if Pos.Pos > 0 and Pos.Pos <= Pos.Last then return Pos.List.Get_Select_Item (Pos.Pos); else return UISelectItem'Class (Pos.Current.all).Get_Select_Item (Context); end if; end Element; -- ------------------------------ -- Move to the next child. -- ------------------------------ procedure Next (Pos : in out Cursor; Context : in Faces_Context'Class) is begin if Pos.Pos > 0 and Pos.Pos < Pos.Last then Pos.Pos := Pos.Pos + 1; else Pos.Pos := 0; loop Pos.Current := null; ASF.Components.Base.Next (Pos.Component); exit when not ASF.Components.Base.Has_Element (Pos.Component); Pos.Current := ASF.Components.Base.Element (Pos.Component); exit when Pos.Current.all in UISelectItem'Class; if Pos.Current.all in UISelectItems'Class then Pos.List := UISelectItems'Class (Pos.Current.all).Get_Select_Item_List (Context); Pos.Last := Pos.List.Length; Pos.Pos := 1; exit when Pos.Last > 0; Pos.Pos := 0; end if; end loop; end if; end Next; -- ------------------------------ -- Get the <b>Select_Item</b> represented by the component. -- ------------------------------ function Get_Select_Item (From : in UISelectItem; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is use Util.Beans.Objects; Val : constant Object := From.Get_Attribute (Name => VALUE_NAME, Context => Context); begin if not Is_Null (Val) then return ASF.Models.Selects.To_Select_Item (Val); end if; declare Label : constant Object := From.Get_Attribute (Name => ITEM_LABEL_NAME, Context => Context); Value : constant Object := From.Get_Attribute (Name => ITEM_VALUE_NAME, Context => Context); Description : constant Object := From.Get_Attribute (Name => ITEM_DESCRIPTION_NAME, Context => Context); Disabled : constant Boolean := From.Get_Attribute (Name => ITEM_DISABLED_NAME, Context => Context); begin if Is_Null (Label) then return ASF.Models.Selects.Create_Select_Item (Value, Value, Description, Disabled); else return ASF.Models.Selects.Create_Select_Item (Label, Value, Description, Disabled); end if; end; end Get_Select_Item; -- ------------------------------ -- UISelectItems Component -- ------------------------------ -- ------------------------------ -- Get the <b>Select_Item</b> represented by the component. -- ------------------------------ function Get_Select_Item_List (From : in UISelectItems; Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item_List is use Util.Beans.Objects; Value : constant Object := From.Get_Attribute (Name => VALUE_NAME, Context => Context); begin return ASF.Models.Selects.To_Select_Item_List (Value); end Get_Select_Item_List; -- ------------------------------ -- SelectOne Component -- ------------------------------ -- ------------------------------ -- Render the <b>select</b> element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UISelectOne; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UISelectOne'Class (UI).Render_Select (Context); end if; end Encode_Begin; -- ------------------------------ -- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if -- the component is rendered. -- ------------------------------ procedure Render_Select (UI : in UISelectOne; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value; begin Writer.Start_Element ("select"); Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id); UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer); UISelectOne'Class (UI).Render_Options (Value, Context); Writer.End_Element ("select"); end Render_Select; -- ------------------------------ -- Renders the <b>option</b> element. This is called by <b>Render_Select</b> to -- generate the component options. -- ------------------------------ procedure Render_Options (UI : in UISelectOne; Value : in Util.Beans.Objects.Object; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value); Iter : Cursor; begin UI.First (Context, Iter); while Has_Element (Iter) loop declare Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context); Item_Value : constant Wide_Wide_String := Item.Get_Value; begin Writer.Start_Element ("option"); Writer.Write_Wide_Attribute ("value", Item_Value); if Item_Value = Selected then Writer.Write_Attribute ("selected", "selected"); end if; if Item.Is_Escaped then Writer.Write_Wide_Text (Item.Get_Label); else Writer.Write_Wide_Text (Item.Get_Label); end if; Writer.End_Element ("option"); Next (Iter, Context); end; end loop; end Render_Options; -- ------------------------------ -- Returns True if the radio options must be rendered vertically. -- ------------------------------ function Is_Vertical (UI : in UISelectOneRadio; Context : in Faces_Context'Class) return Boolean is Dir : constant String := UI.Get_Attribute (Context => Context, Name => "layout", Default => ""); begin return Dir = "pageDirection"; end Is_Vertical; -- ------------------------------ -- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if -- the component is rendered. -- ------------------------------ overriding procedure Render_Select (UI : in UISelectOneRadio; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value; Vertical : constant Boolean := UI.Is_Vertical (Context); Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value); Iter : Cursor; Id : constant String := To_String (UI.Get_Client_Id); N : Natural := 0; Disabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context, Name => "disabledClass"); Enabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context, Name => "enabledClass"); begin Writer.Start_Element ("table"); UI.Render_Attributes (Context, Writer); if not Vertical then Writer.Start_Element ("tr"); end if; UI.First (Context, Iter); while Has_Element (Iter) loop declare Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context); Item_Value : constant Wide_Wide_String := Item.Get_Value; begin if Vertical then Writer.Start_Element ("tr"); end if; Writer.Start_Element ("td"); -- Render the input radio checkbox. Writer.Start_Element ("input"); Writer.Write_Attribute ("type", "radio"); Writer.Write_Attribute ("name", Id); if Item.Is_Disabled then Writer.Write_Attribute ("disabled", "disabled"); end if; Writer.Write_Attribute ("id", Id & "_" & Util.Strings.Image (N)); Writer.Write_Wide_Attribute ("value", Item_Value); if Item_Value = Selected then Writer.Write_Attribute ("checked", "checked"); end if; Writer.End_Element ("input"); -- Render the label associated with the checkbox. Writer.Start_Element ("label"); if Item.Is_Disabled then if not Util.Beans.Objects.Is_Null (Disabled_Class) then Writer.Write_Attribute ("class", Disabled_Class); end if; else if not Util.Beans.Objects.Is_Null (Enabled_Class) then Writer.Write_Attribute ("class", Enabled_Class); end if; end if; Writer.Write_Attribute ("for", Id & "_" & Util.Strings.Image (N)); if Item.Is_Escaped then Writer.Write_Wide_Text (Item.Get_Label); else Writer.Write_Wide_Text (Item.Get_Label); end if; Writer.End_Element ("label"); Writer.End_Element ("td"); if Vertical then Writer.End_Element ("tr"); end if; Next (Iter, Context); N := N + 1; end; end loop; if not Vertical then Writer.End_Element ("tr"); end if; Writer.End_Element ("table"); end Render_Select; begin ASF.Utils.Set_Text_Attributes (SELECT_ATTRIBUTE_NAMES); ASF.Utils.Set_Interactive_Attributes (SELECT_ATTRIBUTE_NAMES); end ASF.Components.Html.Selects;
Fix the radio button HTML, the input 'name' attribute was missing
Fix the radio button HTML, the input 'name' attribute was missing
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a108f81c875229b92d3f875af3d5b9dfbfdda39d
src/security-auth.adb
src/security-auth.adb
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : Manager_Access; begin if Provider = PROVIDER_OPENID then Impl := new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then Impl := new Security.Auth.OAuth.Facebook.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- 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) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; end Security.Auth;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : Manager_Access; begin if Provider = PROVIDER_OPENID then Impl := new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then Impl := new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then Impl := new Security.Auth.OAuth.Googleplus.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- 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) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; end Security.Auth;
Use the Google+ implementation
Use the Google+ implementation
Ada
apache-2.0
Letractively/ada-security
45326ba268634cddd32d4724eae4f7d1bb3679d3
src/security-oauth-file_registry.ads
src/security-oauth-file_registry.ads
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.OAuth.Servers; private with Util.Strings.Maps; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; type File_Realm_Manager is new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; end record; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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 Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.OAuth.Servers; private with Util.Strings.Maps; private with Security.Random; package Security.OAuth.File_Registry is type File_Principal is new Security.Principal with private; type File_Principal_Access is access all File_Principal'Class; -- Get the principal name. overriding function Get_Name (From : in File_Principal) return String; type File_Application_Manager is new Servers.Application_Manager with private; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class; -- Add the application to the application repository. procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application); type File_Realm_Manager is limited new Servers.Realm_Manager with private; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean); -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access); overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access); overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access); -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String; -- Add a username with the associated password. procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String); private use Ada.Strings.Unbounded; package Application_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Servers.Application, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Servers."="); package Token_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Principal_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package User_Maps renames Util.Strings.Maps; type File_Principal is new Security.Principal with record Token : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Application_Manager is new Servers.Application_Manager with record Applications : Application_Maps.Map; end record; type File_Realm_Manager is limited new Servers.Realm_Manager with record Users : User_Maps.Map; Tokens : Token_Maps.Map; Random : Security.Random.Generator; Token_Bits : Positive := 256; end record; end Security.OAuth.File_Registry;
Declare the Add_Application procedure Declare the Crypt_Password and Add_User procedures
Declare the Add_Application procedure Declare the Crypt_Password and Add_User procedures
Ada
apache-2.0
stcarrez/ada-security
18ca9de28f1c7c61cfe3c0ce68b1dd45e47623ee
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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 & ".Head", Test_Http_Head'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options", Test_Http_Options'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Patch", Test_Http_Patch'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'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) = "HEAD" then Into.Method := HEAD; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; elsif L (L'First .. Pos - 1) = "OPTIONS" then Into.Method := OPTIONS; elsif L (L'First .. Pos - 1) = "PATCH" then Into.Method := PATCH; 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; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; 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; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (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); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); 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; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- 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 HEAD operation. -- ------------------------------ procedure Test_Http_Head (T : in out Test) is Request : Client; Reply : Response; begin Request.Head ("http://www.google.com", Reply); Request.Set_Timeout (5.0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_head.txt"), Reply, True); T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- 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_Head; -- ------------------------------ -- 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; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "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_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "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, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http OPTIONS operation. -- ------------------------------ procedure Test_Http_Options (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Options (Uri & "/options", Reply); T.Assert (T.Server.Method = OPTIONS, "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, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Options; -- ------------------------------ -- Test the http PATCH operation. -- ------------------------------ procedure Test_Http_Patch (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Patch on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Patch (Uri & "/patch", "patch-content", Reply); T.Assert (T.Server.Method = PATCH, "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, 200, Reply.Get_Status, "Invalid status response"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); end Test_Http_Patch; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 & ".Head", Test_Http_Head'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Put", Test_Http_Put'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Delete", Test_Http_Delete'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Options", Test_Http_Options'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Patch", Test_Http_Patch'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get (timeout)", Test_Http_Timeout'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) = "HEAD" then Into.Method := HEAD; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; elsif L (L'First .. Pos - 1) = "OPTIONS" then Into.Method := OPTIONS; elsif L (L'First .. Pos - 1) = "PATCH" then Into.Method := PATCH; 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; -- Don't answer if we check the timeout. if Into.Test_Timeout then return; 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; elsif L'Length = 2 then declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 204 No Content" & ASCII.CR & ASCII.LF); Output.Write (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); Request.Set_Timeout (5.0); Request.Set_Header ("Accept", "text/html"); Util.Http.Add_Int_Header (Request, "DNT", 0); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); 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; T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- 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 HEAD operation. -- ------------------------------ procedure Test_Http_Head (T : in out Test) is Request : Client; Reply : Response; begin Request.Head ("http://www.google.com", Reply); Request.Set_Timeout (5.0); Request.Add_Header ("Accept", "text/html"); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & Natural'Image (Reply.Get_Status)); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_head.txt"), Reply, True); T.Assert (Reply.Contains_Header ("Content-Type"), "Header Content-Type not found"); T.Assert (not Reply.Contains_Header ("Content-Type-Invalid-Missing"), "Some invalid header found"); -- 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_Head; -- ------------------------------ -- 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; -- ------------------------------ -- Test the http PUT operation. -- ------------------------------ procedure Test_Http_Put (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Put on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Put (Uri & "/put", "p1=1", Reply); T.Assert (T.Server.Method = PUT, "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_put.txt"), Reply, True); end Test_Http_Put; -- ------------------------------ -- Test the http DELETE operation. -- ------------------------------ procedure Test_Http_Delete (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Delete (Uri & "/delete", Reply); T.Assert (T.Server.Method = DELETE, "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, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Delete; -- ------------------------------ -- Test the http OPTIONS operation. -- ------------------------------ procedure Test_Http_Options (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Delete on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Options (Uri & "/options", Reply); T.Assert (T.Server.Method = OPTIONS, "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, "", Reply.Get_Body, "Invalid response"); Util.Tests.Assert_Equals (T, 204, Reply.Get_Status, "Invalid status response"); end Test_Http_Options; -- ------------------------------ -- Test the http PATCH operation. -- ------------------------------ procedure Test_Http_Patch (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Patch on " & Uri); T.Server.Method := UNKNOWN; Request.Add_Header ("Content-Type", "application/x-www-form-urlencoded"); Request.Set_Timeout (1.0); T.Assert (Request.Contains_Header ("Content-Type"), "Missing Content-Type"); Request.Patch (Uri & "/patch", "patch-content", Reply); T.Assert (T.Server.Method = PATCH, "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, 200, Reply.Get_Status, "Invalid status response"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); end Test_Http_Patch; -- ------------------------------ -- Test the http timeout. -- ------------------------------ procedure Test_Http_Timeout (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Timeout on " & Uri); T.Server.Test_Timeout := True; T.Server.Method := UNKNOWN; Request.Set_Timeout (0.5); begin Request.Get (Uri & "/timeout", Reply); T.Fail ("No Connection_Error exception raised"); exception when Connection_Error => null; end; end Test_Http_Timeout; end Util.Http.Clients.Tests;
Add some headers in http requests for the tests
Add some headers in http requests for the tests
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
099e199981c15d7af5baa5b825382665d8d306dd
src/gen-model-list.adb
src/gen-model-list.adb
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant EL.Beans.Readonly_Bean_Access := Current.all'Access; begin From.Value_Bean := EL.Objects.To_Object (Bean); end; else From.Value_Bean := EL.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : List_Definition) return EL.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : List_Definition; Name : String) return EL.Objects.Object is pragma Unreferenced (Name); pragma Unreferenced (From); begin return EL.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; end Gen.Model.List;
----------------------------------------------------------------------- -- gen-model-list -- List bean interface for model objects -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.List is -- ------------------------------ -- Get the first item of the list -- ------------------------------ function First (Def : List_Definition) return Cursor is begin return Def.Nodes.First; end First; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : List_Definition) return Natural is Count : constant Natural := Natural (From.Nodes.Length); begin return Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Definition; Index : in Natural) is begin From.Row := Index; if Index > 0 then declare Current : constant T_Access := From.Nodes.Element (Index - 1); Bean : constant EL.Beans.Readonly_Bean_Access := Current.all'Access; begin From.Value_Bean := EL.Objects.To_Object (Bean); end; else From.Value_Bean := EL.Objects.Null_Object; end if; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : List_Definition) return EL.Objects.Object is begin return From.Value_Bean; end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : List_Definition; Name : String) return EL.Objects.Object is begin if Name = "size" then return EL.Objects.To_Object (From.Get_Count); end if; return EL.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Append the item in the list -- ------------------------------ procedure Append (Def : in out List_Definition; Item : in T_Access) is begin Def.Nodes.Append (Item); end Append; end Gen.Model.List;
Add a 'size' attribute to value lists
Add a 'size' attribute to value lists
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
7a67217b1fa31e7d2e2fa4480b39f47e4c17b615
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- 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;
----------------------------------------------------------------------- -- 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.Services.Contexts; with AWA.Applications; package body AWA.Modules is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- 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 Ctx : constant ASC.Service_Context_Access := ASC.Current; begin return ASC.Get_Session (Ctx); end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is Ctx : constant ASC.Service_Context_Access := ASC.Current; begin return ASC.Get_Master_Session (Ctx); 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;
Update Get_Session and Get_Master_Session to get the database session by using the service context
Update Get_Session and Get_Master_Session to get the database session by using the service context
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
647798f52078e4b284848673821b8b5cd8718285
mat/src/memory/mat-memory.ads
mat/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Ptr; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); -- Memory allocation objects are stored in an AVL tree sorted -- on the memory slot address. -- subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- -- subtype Allocation_Ref is Allocation_AVL.Iterator; -- -- Type representing a reference to a memory allocation slot. -- -- use Allocation_AVL; -- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref); -- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees; -- package Allocation_Ref_AVL is -- new Allocation_Ref_Trees.AVL (Key => Target_Addr, -- Storage => Global_Heap.Storage); -- -- Tree of references to memory allocation objects. -- -- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree; -- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator; private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); -- Memory allocation objects are stored in an AVL tree sorted -- on the memory slot address. -- subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- -- subtype Allocation_Ref is Allocation_AVL.Iterator; -- -- Type representing a reference to a memory allocation slot. -- -- use Allocation_AVL; -- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref); -- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees; -- package Allocation_Ref_AVL is -- new Allocation_Ref_Trees.AVL (Key => Target_Addr, -- Storage => Global_Heap.Storage); -- -- Tree of references to memory allocation objects. -- -- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree; -- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator; private end MAT.Memory;
Use Frame_Type type
Use Frame_Type type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8e1ae5e3ad6bd0cf2fa107ed88d94c19bb320291
src/wiki-render.adb
src/wiki-render.adb
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Render is -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Exists := True; end Make_Page_Link; -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish; end Render; end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Render is -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is pragma Unreferenced (Renderer); begin URI := To_Unbounded_Wide_Wide_String (Link); Exists := True; end Make_Page_Link; -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish (Doc); end Render; end Wiki.Render;
Add the document to the Finish procedure
Add the document to the Finish procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
939dedbf66f60bf6318799c770b12af0428ddaaa
src/asf-components-widgets-panels.adb
src/asf-components-widgets-panels.adb
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is procedure Render_Action_Icon (Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Name : in String) is begin Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#"); Writer.Write_Attribute ("class", "ui-panel-icon ui-corner-all ui-state-default"); Writer.Start_Element ("span"); Writer.Write_Attribute ("class", Name); Writer.End_Element ("span"); Writer.End_Element ("a"); end Render_Action_Icon; -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; Closable : constant Boolean := UI.Get_Attribute (CLOSABLE_ATTR_NAME, Context); Toggleable : constant Boolean := UI.Get_Attribute (TOGGLEABLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header ui-widget-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; if Closable then Render_Action_Icon (Writer, "ui-icon ui-icon-closethick"); end if; if Toggleable then Render_Action_Icon (Writer, "ui-icon ui-icon-minusthick"); end if; Writer.End_Element ("div"); -- Write the javascript to support the close and toggle actions. if Closable or Toggleable then Writer.Queue_Script ("$(""#"); Writer.Queue_Script (UI.Get_Client_Id); Writer.Queue_Script (""").panel();"); end if; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer ui-widget-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); declare use Util.Beans.Objects; Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); begin if not Util.Beans.Objects.Is_Null (Class) then Writer.Write_Attribute ("class", To_String (Class) & " ui-panel ui-widget ui-corner-all"); else Writer.Write_Attribute ("class", "ui-panel ui-widget ui-corner-all"); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; end; UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content ui-widget-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is procedure Render_Action_Icon (Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Name : in String); procedure Render_Action_Icon (Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Name : in String) is begin Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#"); Writer.Write_Attribute ("class", "ui-panel-icon ui-corner-all ui-state-default"); Writer.Start_Element ("span"); Writer.Write_Attribute ("class", Name); Writer.End_Element ("span"); Writer.End_Element ("a"); end Render_Action_Icon; -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; Closable : constant Boolean := UI.Get_Attribute (CLOSABLE_ATTR_NAME, Context); Toggleable : constant Boolean := UI.Get_Attribute (TOGGLEABLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header ui-widget-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; if Closable then Render_Action_Icon (Writer, "ui-icon ui-icon-closethick"); end if; if Toggleable then Render_Action_Icon (Writer, "ui-icon ui-icon-minusthick"); end if; Writer.End_Element ("div"); -- Write the javascript to support the close and toggle actions. if Closable or Toggleable then Writer.Queue_Script ("$(""#"); Writer.Queue_Script (UI.Get_Client_Id); Writer.Queue_Script (""").panel();"); end if; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer ui-widget-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); declare use Util.Beans.Objects; Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); begin if not Util.Beans.Objects.Is_Null (Class) then Writer.Write_Attribute ("class", To_String (Class) & " ui-panel ui-widget ui-corner-all"); else Writer.Write_Attribute ("class", "ui-panel ui-widget ui-corner-all"); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; end; UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content ui-widget-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
Declare the Render_Action_Icon procedure
Declare the Render_Action_Icon procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
356190482a8b8f90b4991933ce2e66cd55c5ca57
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value)); end Print_Field; end MAT.Consoles;
Implement the Print_Field operation for an Unbounded_String
Implement the Print_Field operation for an Unbounded_String
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
81757ab16f470711e74561145d7b1d3d89246bed
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client 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.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is -- ------------------------------ -- 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; 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; if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); 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] [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"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("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:") 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 '*' => 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 loop declare Line : constant String := Readline.Get_Line ("matp>"); begin 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; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client 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.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; 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 (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); end Finalize; -- ------------------------------ -- 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; 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; if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); 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] [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"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("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:") 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 '*' => 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 loop declare Line : constant String := Readline.Get_Line ("matp>"); begin 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;
Implement the Finalize for Target_Process_Type and Target_Type objects
Implement the Finalize for Target_Process_Type and Target_Type objects
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
043d6ad5de9cefc4b391c2f212e365950f3557dc
src/asf-components-html-factory.adb
src/asf-components-html-factory.adb
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Html.Links; with ASF.Components.Html.Panels; with ASF.Components.Html.Forms; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is use ASF.Components.Base; function Create_Output return UIComponent_Access; function Create_Output_Link return UIComponent_Access; function Create_Output_Format return UIComponent_Access; function Create_Label return UIComponent_Access; function Create_List return UIComponent_Access; function Create_PanelGroup return UIComponent_Access; function Create_Form return UIComponent_Access; function Create_Input return UIComponent_Access; function Create_Command return UIComponent_Access; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create an UIOutputLink component -- ------------------------------ function Create_Output_Link return UIComponent_Access is begin return new ASF.Components.Html.Links.UIOutputLink; end Create_Output_Link; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output_Format return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputFormat; end Create_Output_Format; -- ------------------------------ -- Create a label component -- ------------------------------ function Create_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UILabel; end Create_Label; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; -- ------------------------------ -- Create an UIPanelGroup component -- ------------------------------ function Create_PanelGroup return UIComponent_Access is begin return new ASF.Components.Html.Panels.UIPanelGroup; end Create_PanelGroup; -- ------------------------------ -- Create an UIForm component -- ------------------------------ function Create_Form return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIForm; end Create_Form; -- ------------------------------ -- Create an UIInput component -- ------------------------------ function Create_Input return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput; end Create_Input; -- ------------------------------ -- Create an UICommand component -- ------------------------------ function Create_Command return UIComponent_Access is begin return new ASF.Components.Html.Forms.UICommand; end Create_Command; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; COMMAND_BUTTON_TAG : aliased constant String := "commandButton"; FORM_TAG : aliased constant String := "form"; INPUT_TAG : aliased constant String := "input"; LABEL_TAG : aliased constant String := "label"; LIST_TAG : aliased constant String := "list"; OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat"; OUTPUT_LINK_TAG : aliased constant String := "outputLink"; OUTPUT_TEXT_TAG : aliased constant String := "outputText"; PANEL_GROUP_TAG : aliased constant String := "panelGroup"; Html_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => COMMAND_BUTTON_TAG'Access, Component => Create_Command'Access, Tag => Create_Component_Node'Access), 2 => (Name => FORM_TAG'Access, Component => Create_Form'Access, Tag => Create_Component_Node'Access), 3 => (Name => INPUT_TAG'Access, Component => Create_Input'Access, Tag => Create_Component_Node'Access), 4 => (Name => LABEL_TAG'Access, Component => Create_Label'Access, Tag => Create_Component_Node'Access), 5 => (Name => LIST_TAG'Access, Component => Create_List'Access, Tag => Create_Component_Node'Access), 6 => (Name => OUTPUT_FORMAT_TAG'Access, Component => Create_Output_Format'Access, Tag => Create_Component_Node'Access), 7 => (Name => OUTPUT_LINK_TAG'Access, Component => Create_Output_Link'Access, Tag => Create_Component_Node'Access), 8 => (Name => OUTPUT_TEXT_TAG'Access, Component => Create_Output'Access, Tag => Create_Component_Node'Access), 9 => (Name => PANEL_GROUP_TAG'Access, Component => Create_PanelGroup'Access, Tag => Create_Component_Node'Access) ); Html_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Html_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Html_Factory'Access; end Definition; end ASF.Components.Html.Factory;
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- 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 ASF.Components.Base; with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Html.Links; with ASF.Components.Html.Panels; with ASF.Components.Html.Forms; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is use ASF.Components.Base; function Create_Output return UIComponent_Access; function Create_Output_Link return UIComponent_Access; function Create_Output_Format return UIComponent_Access; function Create_Label return UIComponent_Access; function Create_List return UIComponent_Access; function Create_PanelGroup return UIComponent_Access; function Create_Form return UIComponent_Access; function Create_Input return UIComponent_Access; function Create_Command return UIComponent_Access; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create an UIOutputLink component -- ------------------------------ function Create_Output_Link return UIComponent_Access is begin return new ASF.Components.Html.Links.UIOutputLink; end Create_Output_Link; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output_Format return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutputFormat; end Create_Output_Format; -- ------------------------------ -- Create a label component -- ------------------------------ function Create_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UILabel; end Create_Label; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; -- ------------------------------ -- Create an UIPanelGroup component -- ------------------------------ function Create_PanelGroup return UIComponent_Access is begin return new ASF.Components.Html.Panels.UIPanelGroup; end Create_PanelGroup; -- ------------------------------ -- Create an UIForm component -- ------------------------------ function Create_Form return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIForm; end Create_Form; -- ------------------------------ -- Create an UIInput component -- ------------------------------ function Create_Input return UIComponent_Access is begin return new ASF.Components.Html.Forms.UIInput; end Create_Input; -- ------------------------------ -- Create an UICommand component -- ------------------------------ function Create_Command return UIComponent_Access is begin return new ASF.Components.Html.Forms.UICommand; end Create_Command; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; COMMAND_BUTTON_TAG : aliased constant String := "commandButton"; FORM_TAG : aliased constant String := "form"; INPUT_SECRET_TAG : aliased constant String := "inputSecret"; INPUT_TEXT_TAG : aliased constant String := "inputText"; LABEL_TAG : aliased constant String := "label"; LIST_TAG : aliased constant String := "list"; OUTPUT_FORMAT_TAG : aliased constant String := "outputFormat"; OUTPUT_LINK_TAG : aliased constant String := "outputLink"; OUTPUT_TEXT_TAG : aliased constant String := "outputText"; PANEL_GROUP_TAG : aliased constant String := "panelGroup"; Html_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => COMMAND_BUTTON_TAG'Access, Component => Create_Command'Access, Tag => Create_Component_Node'Access), 2 => (Name => FORM_TAG'Access, Component => Create_Form'Access, Tag => Create_Component_Node'Access), 3 => (Name => INPUT_SECRET_TAG'Access, Component => Create_Input'Access, Tag => Create_Component_Node'Access), 4 => (Name => INPUT_TEXT_TAG'Access, Component => Create_Input'Access, Tag => Create_Component_Node'Access), 5 => (Name => LABEL_TAG'Access, Component => Create_Label'Access, Tag => Create_Component_Node'Access), 6 => (Name => LIST_TAG'Access, Component => Create_List'Access, Tag => Create_Component_Node'Access), 7 => (Name => OUTPUT_FORMAT_TAG'Access, Component => Create_Output_Format'Access, Tag => Create_Component_Node'Access), 8 => (Name => OUTPUT_LINK_TAG'Access, Component => Create_Output_Link'Access, Tag => Create_Component_Node'Access), 9 => (Name => OUTPUT_TEXT_TAG'Access, Component => Create_Output'Access, Tag => Create_Component_Node'Access), 10 => (Name => PANEL_GROUP_TAG'Access, Component => Create_PanelGroup'Access, Tag => Create_Component_Node'Access) ); Html_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Html_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Html_Factory'Access; end Definition; end ASF.Components.Html.Factory;
Rename h:input into h:inputText and add h:inputSecret
Rename h:input into h:inputText and add h:inputSecret
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a2f3ef5384015913a6925fdf5f69048d7fb97ed8
regtests/util-events-timers-tests.adb
regtests/util-events-timers-tests.adb
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat", Test_Repeat_Timer'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; if Sub.Repeat > 1 then Sub.Repeat := Sub.Repeat - 1; Event.Repeat (Ada.Real_Time.Milliseconds (1)); end if; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; -- ----------------------- -- Test repeating timers. -- ----------------------- procedure Test_Repeat_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Count := 0; T.Repeat := 5; for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); loop delay until Deadline; M.Process (Deadline); exit when Deadline >= Now + Ada.Real_Time.Seconds (1); end loop; Assert_Equals (T, 5, T.Count, "The timer handler was not repeated"); end Test_Repeat_Timer; end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat", Test_Repeat_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process", Test_Many_Timers'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; if Sub.Repeat > 1 then Sub.Repeat := Sub.Repeat - 1; Event.Repeat (Ada.Real_Time.Milliseconds (1)); end if; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; -- ----------------------- -- Test repeating timers. -- ----------------------- procedure Test_Repeat_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Count := 0; T.Repeat := 5; for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); loop delay until Deadline; M.Process (Deadline); exit when Deadline >= Now + Ada.Real_Time.Seconds (1); end loop; Assert_Equals (T, 5, T.Count, "The timer handler was not repeated"); end Test_Repeat_Timer; -- ----------------------- -- Test executing several timers. -- ----------------------- procedure Test_Many_Timers (T : in out Test) is Timer_Count : constant Positive := 30; type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref; type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test; M : Timer_List; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; R : Timer_Ref_Array; D : Test_Ref_Array; Dt : Ada.Real_Time.Time_Span; Count : Natural := 0; begin for I in R'Range loop D (I).Count := 0; D (I).Repeat := 4; if I mod 2 = 0 then Dt := Ada.Real_Time.Milliseconds (40); else Dt := Ada.Real_Time.Milliseconds (20); end if; M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt); end loop; loop M.Process (Deadline); exit when Deadline >= Start + Ada.Real_Time.Seconds (10); Count := Count + 1; delay until Deadline; end loop; Util.Tests.Assert_Equals (T, 4, Count, "Count of Process"); for I in D'Range loop Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at " & Natural'Image (I) & " " & Natural'Image (Count)); end loop; end Test_Many_Timers; end Util.Events.Timers.Tests;
Implement the Test_Many_Timers procedure and register it for execution
Implement the Test_Many_Timers procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
728e51561feeb788a150f7f93c30c2c4d16ab87d
src/sys/processes/util-processes.ads
src/sys/processes/util-processes.ads
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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); -- Set the environment variable to be used by the process before its creation. procedure Set_Environment (Proc : in out Process; Name : in String; Value : in String); procedure Set_Environment (Proc : in out Process; Iterate : not null access procedure (Process : not null access procedure (Name : in String; Value : 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; -- Clear the program arguments. procedure Clear_Arguments (Sys : in out System_Process) 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 environment variable to be used by the process before its creation. procedure Set_Environment (Sys : in out System_Process; Name : in String; Value : 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;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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); -- Set the environment variable to be used by the process before its creation. procedure Set_Environment (Proc : in out Process; Name : in String; Value : in String); procedure Set_Environment (Proc : in out Process; Iterate : not null access procedure (Process : not null access procedure (Name : in String; Value : 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; Mode : in Pipe_Mode := NONE); procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE); procedure Spawn (Proc : in out Process; 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; -- Clear the program arguments. procedure Clear_Arguments (Sys : in out System_Process) 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 environment variable to be used by the process before its creation. procedure Set_Environment (Sys : in out System_Process; Name : in String; Value : 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;
Add a Spawn procedure
Add a Spawn procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5dde9635dacad2102ffbb8d6dc937c094c1377cd
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 -- 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 new Ada.Finalization.Limited_Controlled with 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; -- Release the target process instance. overriding procedure Finalize (Target : in out Target_Process_Type); 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; -- Release the storage used by the target object. overriding procedure Finalize (Target : in out Target_Type); 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; with MAT.Expressions; 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 new Ada.Finalization.Limited_Controlled and MAT.Expressions.Resolver_Type with 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; -- Release the target process instance. overriding procedure Finalize (Target : in out Target_Process_Type); -- 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; -- 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; 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; -- Release the storage used by the target object. overriding procedure Finalize (Target : in out Target_Type); end MAT.Targets;
Change Target_Process_Type to implement the Resolver_Type interface
Change Target_Process_Type to implement the Resolver_Type interface
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8ecd447c152ecf522ee88c92312b238360960812
mat/src/gtk/mat-callbacks.ads
mat/src/gtk/mat-callbacks.ads
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with Gtkada.Builder; package MAT.Callbacks is -- Callback executed when the "quit" action is executed from the menu. procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); end MAT.Callbacks;
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with Gtkada.Builder; package MAT.Callbacks is -- Callback executed when the "quit" action is executed from the menu. procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "about" action is executed from the menu. procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); end MAT.Callbacks;
Declare the On_Menu_About procedure
Declare the On_Menu_About procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
49802c8701e54dda230c9953b0a42d59e76ea6cf
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 Ada.Containers; with ADO; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; 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 pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Utils.To_Identifier (Value)); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; 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 pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Use the ADO.Utils.To_Identifier operation
Use the ADO.Utils.To_Identifier operation
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
62910a73b5468a028c6e802bc165ec079e956549
awa/plugins/awa-storages/src/awa-storages-beans.ads
awa/plugins/awa-storages/src/awa-storages-beans.ads
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- 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; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- 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; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
Declare the Load_Files procedure
Declare the Load_Files procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5fa82bb86966002eda1b53c527d33956498a6487
regtests/gen-artifacts-xmi-tests.adb
regtests/gen-artifacts-xmi-tests.adb
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is use Ada.Strings.Unbounded; package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Tag_Definition'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is procedure Check (Namespace : in String; Name : in String; Id : in String); A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element, Element_Type_Access => Stereotype_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; -- Test searching an XMI Tag definition element by using its name. procedure Test_Find_Tag_Definition (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Tag_Definition is new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element, Element_Type_Access => Tag_Definition_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); declare Tag : Tag_Definition_Element_Access; begin Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]", Gen.Model.XMI.BY_NAME); T.Assert (Tag /= null, "Tag definition not found"); end; end Test_Find_Tag_Definition; end Gen.Artifacts.XMI.Tests;
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Gen.Configs; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is use Ada.Strings.Unbounded; package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Tag_Definition'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is procedure Check (Namespace : in String; Name : in String; Id : in String); A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element, Element_Type_Access => Stereotype_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; -- Test searching an XMI Tag definition element by using its name. procedure Test_Find_Tag_Definition (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Tag_Definition is new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element, Element_Type_Access => Tag_Definition_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_Model (G.Get_Parameter (Gen.Configs.GEN_UML_DIR) & "/Dynamo.xmi", G); declare Tag : Tag_Definition_Element_Access; begin Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]", Gen.Model.XMI.BY_NAME); T.Assert (Tag /= null, "Tag definition not found"); end; end Test_Find_Tag_Definition; end Gen.Artifacts.XMI.Tests;
Update the unit test to use Read_Model
Update the unit test to use Read_Model
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
d65cfefd476420585680177efe88668d8356ec9c
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
Fix to use the Nullable_String type
Fix to use the Nullable_String type
Ada
apache-2.0
stcarrez/ada-ado
9f92252fa4844271562a5bab2fe1de6edf36fd92
mat/src/mat-targets.adb
mat/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client 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.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Readers; package body MAT.Targets is -- ------------------------------ -- 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.Readers.Manager_Base'Class) is begin MAT.Targets.Readers.Initialize (Target => Target, Reader => 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; 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; if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); 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] [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"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("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:") 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 '*' => 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 loop declare Line : constant String := Readline.Get_Line ("matp>"); begin 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; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client 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.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is -- ------------------------------ -- 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; 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; if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); 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] [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"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("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:") 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 '*' => 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 loop declare Line : constant String := Readline.Get_Line ("matp>"); begin 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; end MAT.Targets;
Use the MAT.Targets.Probes package
Use the MAT.Targets.Probes package
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
17a10c4ac1c9e290ae0922bf7113a3f30d065136
boards/stm32f769_discovery/stm32-board.ads
boards/stm32f769_discovery/stm32-board.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F7 Discovery kits -- manufactured by ST Microelectronics. with Ada.Interrupts.Names; use Ada.Interrupts; with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.FMC; use STM32.FMC; with STM32.I2C; use STM32.I2C; with STM32.DMA; use STM32.DMA; use STM32; with Touch_Panel_FT6x06; with Framebuffer_OTM8009A; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Red : User_LED renames PJ13; Green : User_LED renames PJ5; LED1 : User_LED renames Red; LED2 : User_LED renames Green; LCH_LED : User_LED renames Red; All_LEDs : GPIO_Points := (Red, Green); procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED) renames STM32.GPIO.Set; procedure Turn_Off (This : in out User_LED) renames STM32.GPIO.Clear; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; -- GPIO Pins for FMC FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG2); FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_NBL : constant GPIO_Points := (PE0, PE1, PI4, PI5); FMC_SDNWE : GPIO_Point renames PH5; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDCLK : GPIO_Point renames PG8; FMC_BA0 : GPIO_Point renames PG4; FMC_BA1 : GPIO_Point renames PG5; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_BA0 & FMC_BA1 & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C000_0000#; SDRAM_Size : constant := 16#0100_0000#; -- 16MB SDRAM SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := STM32.FMC.FMC_RowBits_Number_12b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_2; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 16#0603#; SDRAM_Min_Delay_In_ns : constant := 60; --------- -- I2C -- --------- procedure Initialize_I2C_GPIO (Port : in out I2C_Port) with -- I2C_2 and I2C_4 are not accessible on this board Pre => As_Port_Id (Port) = I2C_Id_1 or else As_Port_Id (Port) = I2C_Id_4; procedure Configure_I2C (Port : in out I2C_Port); -------------------------------- -- Screen/Touch panel devices -- -------------------------------- LCD_Natural_Width : constant := Framebuffer_OTM8009A.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_OTM8009A.LCD_Natural_Height; Display : Framebuffer_OTM8009A.Frame_Buffer; Touch_Panel : Touch_Panel_FT6x06.Touch_Panel; ----------------- -- Touch Panel -- ----------------- I2C1_SCL : GPIO_Point renames PB8; I2C1_SDA : GPIO_Point renames PB9; I2C4_SCL : GPIO_Point renames PD12; I2C4_SDA : GPIO_Point renames PB7; TP_INT : GPIO_Point renames PI13; TP_Pins : constant GPIO_Points := (I2C4_SCL, I2C4_SDA); ----------- -- Audio -- ----------- -- Audio out SAI2_MCLK_A : GPIO_Point renames PI4; SAI2_SCK_A : GPIO_Point renames PI5; SAI2_SD_A : GPIO_Point renames PI6; SAI2_FS_A : GPIO_Point renames PI7; -- Audio in SAI2_SD_B : GPIO_Point renames PG10; -- Audio interrupts TP_PH15 : GPIO_Point renames PH15; Audio_I2C : I2C_Port renames I2C_4; Audio_INT : GPIO_Point renames PD6; Audio_DMA : DMA_Controller renames DMA_2; ----------------- -- User button -- ----------------- User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_ID := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
------------------------------------------------------------------------------ -- -- -- 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 file provides declarations for devices on the STM32F7 Discovery kits -- manufactured by ST Microelectronics. with Ada.Interrupts.Names; use Ada.Interrupts; with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; with STM32.FMC; use STM32.FMC; with STM32.I2C; use STM32.I2C; with STM32.DMA; use STM32.DMA; use STM32; with Touch_Panel_FT6x06; with Framebuffer_OTM8009A; package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Red : User_LED renames PJ13; Green : User_LED renames PJ5; Green2 : User_LED renames PA12; LED1 : User_LED renames Red; LED2 : User_LED renames Green; LED3 : User_LED renames Green2; LCH_LED : User_LED renames Red; All_LEDs : GPIO_Points := (Red, Green, Green2); procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : in out User_LED) renames STM32.GPIO.Set; procedure Turn_Off (This : in out User_LED) renames STM32.GPIO.Clear; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : in out GPIO_Points) renames STM32.GPIO.Toggle; -- GPIO Pins for FMC FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG2); FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_NBL : constant GPIO_Points := (PE0, PE1, PI4, PI5); FMC_SDNWE : GPIO_Point renames PH5; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDCLK : GPIO_Point renames PG8; FMC_BA0 : GPIO_Point renames PG4; FMC_BA1 : GPIO_Point renames PG5; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_BA0 & FMC_BA1 & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C000_0000#; SDRAM_Size : constant := 16#0100_0000#; -- 16MB SDRAM SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := STM32.FMC.FMC_RowBits_Number_12b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_2; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 16#0603#; SDRAM_Min_Delay_In_ns : constant := 60; --------- -- I2C -- --------- procedure Initialize_I2C_GPIO (Port : in out I2C_Port) with -- I2C_2 and I2C_4 are not accessible on this board Pre => As_Port_Id (Port) = I2C_Id_1 or else As_Port_Id (Port) = I2C_Id_4; procedure Configure_I2C (Port : in out I2C_Port); -------------------------------- -- Screen/Touch panel devices -- -------------------------------- LCD_Natural_Width : constant := Framebuffer_OTM8009A.LCD_Natural_Width; LCD_Natural_Height : constant := Framebuffer_OTM8009A.LCD_Natural_Height; Display : Framebuffer_OTM8009A.Frame_Buffer; Touch_Panel : Touch_Panel_FT6x06.Touch_Panel; ----------------- -- Touch Panel -- ----------------- I2C1_SCL : GPIO_Point renames PB8; I2C1_SDA : GPIO_Point renames PB9; I2C4_SCL : GPIO_Point renames PD12; I2C4_SDA : GPIO_Point renames PB7; TP_INT : GPIO_Point renames PI13; TP_Pins : constant GPIO_Points := (I2C4_SCL, I2C4_SDA); ----------- -- Audio -- ----------- -- Audio out SAI1_MCLK_A : GPIO_Point renames PG7; SAI1_SCK_A : GPIO_Point renames PE5; SAI1_SD_A : GPIO_Point renames PE6; SAI1_FS_A : GPIO_Point renames PE4; -- Audio in SAI1_SD_B : GPIO_Point renames PE3; -- Audio interrupts Audio_I2C : I2C_Port renames I2C_4; Audio_INT : GPIO_Point renames PB10; Audio_DMA : DMA_Controller renames DMA_2; ----------------- -- User button -- ----------------- User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_ID := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
Add User LED 3 to the stm32f769 disco board definition.
Add User LED 3 to the stm32f769 disco board definition. Also fix the Audio ports definition for this board.
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
63797f82b4e93c22cfdfef8f4106777eaaed6819
src/gen-artifacts-xmi.ads
src/gen-artifacts-xmi.ads
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- 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. overriding 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; end record; end Gen.Artifacts.XMI;
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- 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 DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- 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. overriding 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
Declare the stereotypes that are used for the generation of ADO/AWA packages and types
Declare the stereotypes that are used for the generation of ADO/AWA packages and types
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
e822b6b47a194a2d251dfc449ea623432309a72f
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 <tt>Output_Buffer_Stream</tt> and <tt>Input_Buffer_Stream</tt> implements an output -- and input stream respectively which manages an output or input buffer. -- -- The <tt>Output_Buffer_Stream</tt> must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. -- -- The <tt>Input_Buffer_Stream</tt> 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. 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;
Document the Input/Output_Buffer_Stream support
Document the Input/Output_Buffer_Stream support
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
546bfac51e4c0984f3598a729475ddd7f770348f
src/sqlite/ado-statements-sqlite.ads
src/sqlite/ado-statements-sqlite.ads
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Stmt : ADO.Drivers.Connections.Sqlite.Sqlite_Access := System.Null_Address; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
----------------------------------------------------------------------- -- ado-statements-sqlite -- SQLite database statements -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with ADO.Drivers.Connections.Sqlite; package ADO.Statements.Sqlite is type Handle is null record; -- ------------------------------ -- Delete statement -- ------------------------------ type Sqlite_Delete_Statement is new Delete_Statement with private; type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Sqlite_Update_Statement is new Update_Statement with private; type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Sqlite_Insert_Statement is new Insert_Statement with private; type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Sqlite_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for SQLite -- ------------------------------ type Sqlite_Query_Statement is new Query_Statement with private; type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class; -- Execute the query overriding procedure Execute (Query : in out Sqlite_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Sqlite_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Sqlite_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Sqlite_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Sqlite_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Sqlite_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Sqlite_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Sqlite_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Sqlite_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Sqlite_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Sqlite_Query_Statement) return Natural; -- Deletes the query statement. overriding procedure Finalize (Query : in out Sqlite_Query_Statement); -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; -- Create the query statement. function Create_Statement (Database : in ADO.Drivers.Connections.Sqlite.Sqlite_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Sqlite_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Stmt : ADO.Drivers.Connections.Sqlite.Sqlite_Access := System.Null_Address; Counter : Natural := 1; Status : State := DONE; Max_Column : Natural; end record; type Sqlite_Delete_Statement is new Delete_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Sqlite_Update_Statement is new Update_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Sqlite_Insert_Statement is new Insert_Statement with record Connection : ADO.Drivers.Connections.Sqlite.Sqlite_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Sqlite;
Fix header title
Fix header title
Ada
apache-2.0
stcarrez/ada-ado
0b8e5722600c00556b6388955c75446c6b6a254a
awa/samples/src/atlas-applications.ads
awa/samples/src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas-applications - Atlas Applications -- 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 AWA.Applications; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Filters.Dump; with ASF.Servlets.Measures; with Security.Openid.Servlets; with AWA.Users.Principals; with AWA.Users.Module; with AWA.Services.Filters; package Atlas.Applications is type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; procedure Initialize (App : in Application_Access); private type Application is new AWA.Applications.Application with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Principals.Verify_Auth_Servlet; User_Module : aliased AWA.Users.Module.User_Module; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas-applications - Atlas Applications -- 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 AWA.Applications; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Filters.Dump; with ASF.Servlets.Measures; with Security.Openid.Servlets; with AWA.Users.Principals; with AWA.Users.Module; with AWA.Comments.Module; with AWA.Services.Filters; package Atlas.Applications is type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; procedure Initialize (App : in Application_Access); private type Application is new AWA.Applications.Application with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Principals.Verify_Auth_Servlet; User_Module : aliased AWA.Users.Module.User_Module; Comment_Module : aliased AWA.Comments.Module.Comment_Module; Perf : aliased ASF.Servlets.Measures.Measure_Servlet; end record; end Atlas.Applications;
Add the comments module in the Atlas application
Add the comments module in the Atlas application
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ef368afaa072e200da97921d049c1a458f448f1f
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- 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) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Assoc.Sql_Name := Name; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; Table.Kind := Gen.Model.Mappings.T_TABLE; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- 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) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Assoc.Sql_Name := Name; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Mark the table type mapping as a T_TABLE
Mark the table type mapping as a T_TABLE
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
63a9baeeead5eb8962e46dbda0de60f772081152
src/asf-requests-mockup.adb
src/asf-requests-mockup.adb
----------------------------------------------------------------------- -- asf.requests.mockup -- ASF Requests mockup -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Requests.Mockup is function Find (Map : in Util.Strings.Maps.Map; Name : in String) return String; -- ------------------------------ -- Find and return the string associated with a key in the map. -- ------------------------------ function Find (Map : in Util.Strings.Maps.Map; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Map.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Find; -- ------------------------------ -- Returns the value of a request parameter as a String, or null if the -- parameter does not exist. Request parameters are extra information sent with -- the request. For HTTP servlets, parameters are contained in the query string -- or posted form data. -- -- You should only use this method when you are sure the parameter has only one -- value. If the parameter might have more than one value, use -- Get_Parameter_Values(String). -- -- If you use this method with a multivalued parameter, the value returned is -- equal to the first value in the array returned by Get_Parameter_Values. -- -- If the parameter data was sent in the request body, such as occurs with -- an HTTP POST request, then reading the body directly via getInputStream() -- or getReader() can interfere with the execution of this method. -- ------------------------------ function Get_Parameter (Req : in Request; Name : in String) return String is begin return Find (Req.Parameters, Name); end Get_Parameter; -- ------------------------------ -- Iterate over the request parameters and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Req.Parameters.Iterate (Process => Process_Wrapper'Access); end Iterate_Parameters; -- ------------------------------ -- Set the parameter -- ------------------------------ procedure Set_Parameter (Req : in out Request; Name : in String; Value : in String) is begin Req.Parameters.Include (Name, Value); end Set_Parameter; -- ------------------------------ -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. -- ------------------------------ function Get_Method (Req : in Request) return String is begin return To_String (Req.Method); end Get_Method; -- ------------------------------ -- Sets the HTTP method. -- ------------------------------ procedure Set_Method (Req : in out Request; Method : in String) is begin Req.Method := To_Unbounded_String (Method); end Set_Method; -- ------------------------------ -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. -- ------------------------------ function Get_Protocol (Req : in Request) return String is begin return To_String (Req.Protocol); end Get_Protocol; -- ------------------------------ -- Sets the protocol version -- ------------------------------ procedure Set_Protocol (Req : in out Request; Protocol : in String) is begin Req.Protocol := To_Unbounded_String (Protocol); end Set_Protocol; -- ------------------------------ -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz -- ------------------------------ function Get_Request_URI (Req : in Request) return String is begin return To_String (Req.URI); end Get_Request_URI; -- ------------------------------ -- Set the request URI. -- ------------------------------ procedure Set_Request_URI (Req : in out Request; URI : in String) is begin Req.URI := To_Unbounded_String (URI); end Set_Request_URI; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Header (Req : in Request; Name : in String) return String is begin return Find (Req.Headers, Name); end Get_Header; -- ------------------------------ -- Sets the header -- ------------------------------ procedure Set_Header (Req : in out Request; Name : in String; Value : in String) is begin Req.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Headers (Req : in Request; Name : in String) return String is begin return Find (Req.Headers, Name); end Get_Headers; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Req.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. -- ------------------------------ function Get_Remote_Addr (Req : in Request) return String is begin return To_String (Req.Peer); end Get_Remote_Addr; -- ------------------------------ -- Sets the peer address -- ------------------------------ procedure Set_Remote_Addr (Req : in out Request; Addr : in String) is begin Req.Peer := To_Unbounded_String (Addr); end Set_Remote_Addr; -- ------------------------------ -- Get the number of parts included in the request. -- ------------------------------ function Get_Part_Count (Req : in Request) return Natural is pragma Unreferenced (Req); begin return 0; end Get_Part_Count; -- ------------------------------ -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is begin null; end Process_Part; -- ------------------------------ -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is begin null; end Process_Part; -- ------------------------------ -- Set the request cookie by using the cookie returned in the response. -- ------------------------------ procedure Set_Cookie (Req : in out Request; From : in ASF.Responses.Mockup.Response'Class) is C : constant String := From.Get_Header ("Set-Cookie"); begin Req.Set_Header ("Cookie", C); end Set_Cookie; end ASF.Requests.Mockup;
----------------------------------------------------------------------- -- asf.requests.mockup -- ASF Requests mockup -- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Requests.Mockup is function Find (Map : in Util.Strings.Maps.Map; Name : in String) return String; -- ------------------------------ -- Find and return the string associated with a key in the map. -- ------------------------------ function Find (Map : in Util.Strings.Maps.Map; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Map.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Find; -- ------------------------------ -- Returns the value of a request parameter as a String, or null if the -- parameter does not exist. Request parameters are extra information sent with -- the request. For HTTP servlets, parameters are contained in the query string -- or posted form data. -- -- You should only use this method when you are sure the parameter has only one -- value. If the parameter might have more than one value, use -- Get_Parameter_Values(String). -- -- If you use this method with a multivalued parameter, the value returned is -- equal to the first value in the array returned by Get_Parameter_Values. -- -- If the parameter data was sent in the request body, such as occurs with -- an HTTP POST request, then reading the body directly via getInputStream() -- or getReader() can interfere with the execution of this method. -- ------------------------------ function Get_Parameter (Req : in Request; Name : in String) return String is begin return Find (Req.Parameters, Name); end Get_Parameter; -- ------------------------------ -- Iterate over the request parameters and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Req.Parameters.Iterate (Process => Process_Wrapper'Access); end Iterate_Parameters; -- ------------------------------ -- Set the parameter -- ------------------------------ procedure Set_Parameter (Req : in out Request; Name : in String; Value : in String) is begin Req.Parameters.Include (Name, Value); end Set_Parameter; -- ------------------------------ -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. -- ------------------------------ function Get_Method (Req : in Request) return String is begin return To_String (Req.Method); end Get_Method; -- ------------------------------ -- Sets the HTTP method. -- ------------------------------ procedure Set_Method (Req : in out Request; Method : in String) is begin Req.Method := To_Unbounded_String (Method); end Set_Method; -- ------------------------------ -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. -- ------------------------------ function Get_Protocol (Req : in Request) return String is begin return To_String (Req.Protocol); end Get_Protocol; -- ------------------------------ -- Sets the protocol version -- ------------------------------ procedure Set_Protocol (Req : in out Request; Protocol : in String) is begin Req.Protocol := To_Unbounded_String (Protocol); end Set_Protocol; -- ------------------------------ -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz -- ------------------------------ function Get_Request_URI (Req : in Request) return String is begin return To_String (Req.URI); end Get_Request_URI; -- ------------------------------ -- Set the request URI. When <tt>Split</tt> is true, the request parameters are -- cleared and initialized with the query parameters passed in the URI. -- ------------------------------ procedure Set_Request_URI (Req : in out Request; URI : in String; Split : in Boolean := False) is begin if not Split then Req.URI := To_Unbounded_String (URI); else Req.Parameters.Clear; declare Sep : Natural := Util.Strings.Index (URI, '?'); Sep2, Pos : Natural; begin if Sep = 0 then Pos := URI'Last; Req.URI := To_Unbounded_String (URI); else Pos := Sep + 1; Req.URI := To_Unbounded_String (URI (URI'First .. Sep - 1)); end if; -- Do a simple parameter identification and split. -- Since this is for a mockup, we don't need full compliance. while Pos < URI'Last loop Sep := Util.Strings.Index (URI, '=', Pos); if Sep = 0 then Req.Set_Parameter (URI (Pos .. URI'Last), ""); exit; end if; Sep2 := Util.Strings.Index (URI, '&', Sep + 1); if Sep2 = 0 then Req.Set_Parameter (URI (Pos .. Sep - 1), URI (Sep + 1 .. URI'Last)); exit; end if; Req.Set_Parameter (URI (Pos .. Sep - 1), URI (Sep + 1 .. Sep2 - 1)); Pos := Sep2 + 1; end loop; end; end if; end Set_Request_URI; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Header (Req : in Request; Name : in String) return String is begin return Find (Req.Headers, Name); end Get_Header; -- ------------------------------ -- Sets the header -- ------------------------------ procedure Set_Header (Req : in out Request; Name : in String; Value : in String) is begin Req.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Headers (Req : in Request; Name : in String) return String is begin return Find (Req.Headers, Name); end Get_Headers; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Req.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. -- ------------------------------ function Get_Remote_Addr (Req : in Request) return String is begin return To_String (Req.Peer); end Get_Remote_Addr; -- ------------------------------ -- Sets the peer address -- ------------------------------ procedure Set_Remote_Addr (Req : in out Request; Addr : in String) is begin Req.Peer := To_Unbounded_String (Addr); end Set_Remote_Addr; -- ------------------------------ -- Get the number of parts included in the request. -- ------------------------------ function Get_Part_Count (Req : in Request) return Natural is pragma Unreferenced (Req); begin return 0; end Get_Part_Count; -- ------------------------------ -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is begin null; end Process_Part; -- ------------------------------ -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is begin null; end Process_Part; -- ------------------------------ -- Set the request cookie by using the cookie returned in the response. -- ------------------------------ procedure Set_Cookie (Req : in out Request; From : in ASF.Responses.Mockup.Response'Class) is C : constant String := From.Get_Header ("Set-Cookie"); begin Req.Set_Header ("Cookie", C); end Set_Cookie; end ASF.Requests.Mockup;
Add Split optional parameter to the Set_Request_URI procedure to clear the request parameters and extract them from the URI
Add Split optional parameter to the Set_Request_URI procedure to clear the request parameters and extract them from the URI
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d0826c2bd9df0bb1b8d4b8f3917a42759e34466a
mat/src/events/mat-events-targets.adb
mat/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos = Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Probe_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos = Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
Implement the Find function to find a event in a list
Implement the Find function to find a event in a list
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f13fefafc51770335b9b07a4085a9da592d6cf22
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- 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) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- 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) is begin Memory.Memory.Find (From, To, Into); end Find; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- 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) is Iter : Region_Info_Cursor; begin Iter := Regions.Floor (From); while Region_Info_Maps.Has_Element (Iter) loop declare Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter); Region : Region_Info; begin exit when Start > To; Region := Region_Info_Maps.Element (Iter); if Region.End_Addr >= From then if not Into.Contains (Start) then Into.Insert (Start, Region); end if; end if; Region_Info_Maps.Next (Iter); end; end loop; end Find; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- 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) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory 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 Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- 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) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- 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) is begin Memory.Memory.Find (From, To, Into); end Find; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- 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) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- 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) is Iter : Region_Info_Cursor; begin Iter := Regions.Ceiling (From); while Region_Info_Maps.Has_Element (Iter) loop declare Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter); Region : Region_Info; begin exit when Start > To; Region := Region_Info_Maps.Element (Iter); if Region.End_Addr >= From then if not Into.Contains (Start) then Into.Insert (Start, Region); end if; end if; Region_Info_Maps.Next (Iter); end; end loop; end Find; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- 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) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Fix the Find procedure to find the memory regions that intersect a range of addresses: use the Ceiling function
Fix the Find procedure to find the memory regions that intersect a range of addresses: use the Ceiling function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7f67cca66b3ef87c94c6916c913b67b0c29d1b6d
src/util-strings-transforms.ads
src/util-strings-transforms.ads
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Unbounded_String; Value : in Character) renames TR.To_Hex; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String; procedure Translate_Xml_Entity (Entity : in String; Into : in out Unbounded_String) renames TR.Translate_Xml_Entity; procedure Unescape_Xml (Content : in String; Translator : not null access procedure (Entity : in String; Into : in out Unbounded_String) := Translate_Xml_Entity'Access; Into : in out Unbounded_String) renames TR.Unescape_Xml; end Util.Strings.Transforms;
----------------------------------------------------------------------- -- util-strings-transforms -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Unbounded_String; Value : in Character) renames TR.To_Hex; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String; procedure Translate_Xml_Entity (Entity : in String; Into : in out Unbounded_String) renames TR.Translate_Xml_Entity; procedure Unescape_Xml (Content : in String; Translator : not null access procedure (Entity : in String; Into : in out Unbounded_String) := Translate_Xml_Entity'Access; Into : in out Unbounded_String) renames TR.Unescape_Xml; end Util.Strings.Transforms;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
dba4b1d808f67b981c5a7190b809a2e6f95de409
src/sys/os-unix/util-systems-os.ads
src/sys/os-unix/util-systems-os.ads
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; end Util.Systems.Os;
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; end Util.Systems.Os;
Fix Errno to use SYMBOL_PREFIX for MacOS
Fix Errno to use SYMBOL_PREFIX for MacOS
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
27c5e9fc14956fac1b8827a625c0e1106eb6d1bf
src/sys/os-windows/util-streams-raw.adb
src/sys/os-windows/util-streams-raw.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with System; with Ada.Text_IO; package body Util.Streams.Raw is use System; use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Get the file descriptor associated with the stream. -- ----------------------- function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type is begin return Stream.File; end Get_File; -- ----------------------- -- Set the file descriptor to be used by the stream. -- ----------------------- procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type) is begin Stream.File := File; end Set_File; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is Error : Integer; begin if Stream.File /= NO_FILE then if Close_Handle (Stream.File) = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Res : aliased DWORD := 0; Status : BOOL; begin Status := Write_File (Stream.File, Buffer'Address, Buffer'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : aliased DWORD := 0; Status : BOOL; Error : Integer; begin Status := Read_File (Stream.File, Into'Address, Into'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with System; package body Util.Streams.Raw is use System; use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Get the file descriptor associated with the stream. -- ----------------------- function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type is begin return Stream.File; end Get_File; -- ----------------------- -- Set the file descriptor to be used by the stream. -- ----------------------- procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type) is begin Stream.File := File; end Set_File; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is Error : Integer; begin if Stream.File /= NO_FILE then if Close_Handle (Stream.File) = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Res : aliased DWORD := 0; Status : BOOL; begin Status := Write_File (Stream.File, Buffer'Address, Buffer'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : aliased DWORD := 0; Status : BOOL; Error : Integer; begin Status := Read_File (Stream.File, Into'Address, Into'Length, Res'Unchecked_Access, System.Null_Address); if Status = 0 then Error := Get_Last_Error; if Error /= ERROR_BROKEN_PIPE then raise Ada.IO_Exceptions.Device_Error with "IO error: " & Integer'Image (Error); end if; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3f800c9873c81937928cf55fe7a039c8a3d236d6
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- util-properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; -- = Property Files = -- The `Util.Properties` package and children implements support to read, write and use -- property files either in the Java property file format or the Windows INI configuration file. -- Each property is assigned a key and a value. The list of properties are stored in the -- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property -- is therefore unique in the list. Properties can be grouped together in sub-properties so -- that a key can represent another list of properties. -- -- == File formats == -- The property file consists of a simple name and value pair separated by the `=` sign. -- Thanks to the Windows INI file format, list of properties can be grouped together -- in sections by using the `[section-name`] notation. -- -- test.count=20 -- test.repeat=5 -- [FileTest] -- test.count=5 -- test.repeat=2 -- -- == Using property files == -- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides -- various operations that can be used. When created, the property manager is empty. One way -- to fill it is by using the `Load_Properties` procedure to read the property file. Another -- way is by using the `Set` procedure to insert or change a property by giving its name -- and its value. -- -- In this example, the property file `test.properties` is loaded and assuming that it contains -- the above configuration example, the `Get ("test.count")` will return the string `"20"`. -- -- with Util.Properties; -- ... -- Props : Util.Properties.Manager; -- ... -- Props.Load_Properties (Path => "test.properties"); -- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count"); -- Props.Set ("test.repeat", "23"); -- Props.Save_Properties (Path => "test.properties"); -- -- To be able to access a section from the property manager, it is necessary to retrieve it -- by using the `Get` function and giving the section name. For example, to retrieve the -- `test.count` property of the `FileTest` section, the following code is used: -- -- FileTest : Util.Properties.Manager := Props.Get ("FileTest"); -- ... -- Ada.Text_IO.Put_Line ("[FileTest] Count: " & FileTest.Get ("test.count"); -- -- @include util-properties-json.ads -- @include util-properties-bundles.ads package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); -- Get the property manager represented by the item value. -- Raise the Conversion_Error exception if the value is not a property manager. function To_Manager (Item : in Value) return Manager; -- Returns True if the item value represents a property manager. function Is_Manager (Item : in Value) return Boolean; private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- util-properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; -- = Property Files = -- The `Util.Properties` package and children implements support to read, write and use -- property files either in the Java property file format or the Windows INI configuration file. -- Each property is assigned a key and a value. The list of properties are stored in the -- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property -- is therefore unique in the list. Properties can be grouped together in sub-properties so -- that a key can represent another list of properties. -- -- == File formats == -- The property file consists of a simple name and value pair separated by the `=` sign. -- Thanks to the Windows INI file format, list of properties can be grouped together -- in sections by using the `[section-name]` notation. -- -- test.count=20 -- test.repeat=5 -- [FileTest] -- test.count=5 -- test.repeat=2 -- -- == Using property files == -- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides -- various operations that can be used. When created, the property manager is empty. One way -- to fill it is by using the `Load_Properties` procedure to read the property file. Another -- way is by using the `Set` procedure to insert or change a property by giving its name -- and its value. -- -- In this example, the property file `test.properties` is loaded and assuming that it contains -- the above configuration example, the `Get ("test.count")` will return the string `"20"`. -- The property `test.repeat` is then modified to have the value `"23"` and the properties are -- then saved in the file. -- -- with Util.Properties; -- ... -- Props : Util.Properties.Manager; -- ... -- Props.Load_Properties (Path => "test.properties"); -- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count"); -- Props.Set ("test.repeat", "23"); -- Props.Save_Properties (Path => "test.properties"); -- -- To be able to access a section from the property manager, it is necessary to retrieve it -- by using the `Get` function and giving the section name. For example, to retrieve the -- `test.count` property of the `FileTest` section, the following code is used: -- -- FileTest : Util.Properties.Manager := Props.Get ("FileTest"); -- ... -- Ada.Text_IO.Put_Line ("[FileTest] Count: " -- & FileTest.Get ("test.count"); -- -- When getting or removing a property, the `NO_PROPERTY` exception is raised if the property -- name was not found in the map. To avoid that exception, it is possible to check whether -- the name is known by using the `Exists` function. -- -- if Props.Exists ("test.old_count") then -- ... -- Property exist -- end if; -- -- @include util-properties-json.ads -- @include util-properties-bundles.ads -- -- == Advance usage of properties == -- The property manager holds the name and value pairs by using an Ada Bean object. -- -- It is possible to iterate over the properties by using the `Iterate` procedure that -- accepts as parameter a `Process` procedure that gets the property name as well as the -- property value. The value itself is passed as an `Util.Beans.Objects.Object` type. -- package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); -- Get the property manager represented by the item value. -- Raise the Conversion_Error exception if the value is not a property manager. function To_Manager (Item : in Value) return Manager; -- Returns True if the item value represents a property manager. function Is_Manager (Item : in Value) return Boolean; private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Add and update the documentation
Add and update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7ae0284e3d8777c6c80894125753b0fb03e28a32
src/base/beans/util-beans-objects-maps.ads
src/base/beans/util-beans-objects-maps.ads
----------------------------------------------------------------------- -- util-beans-objects-maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; type Map_Bean_Access is access all Map_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; -- Iterate over the members of the map. procedure Iterate (From : in Object; Process : not null access procedure (Name : in String; Item : in Object)); private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
----------------------------------------------------------------------- -- util-beans-objects-maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; -- == Object maps == -- The `Util.Beans.Objects.Maps` package provides a map of objects with a `String` -- as index. This allows to associated names to objects. -- To create an instance of the map, it is possible to use the `Create` function -- as follows: -- -- Person : Util.Beans.Objects.Object := Util.Beans.Objects.Maps.Create; -- -- Then, it becomes possible to populate the map with objects by using -- the `Set_Value` procedure as follows: -- -- Util.Beans.Objects.Set_Value (Person, "name", To_Object (Name)); -- Util.Beans.Objects.Set_Value (Person, "last_name", To_Object (Last_Name)); -- Util.Beans.Objects.Set_Value (Person, "age", To_Object (Age)); -- -- Getting a value from the map is done by using the `Get_Value` function: -- -- Name : Util.Beans.Objects.Object := Get_Value (Person, "name"); -- -- It is also possible to iterate over the values of the map by using -- the `Iterate` procedure. package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; type Map_Bean_Access is access all Map_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; -- Iterate over the members of the map. procedure Iterate (From : in Object; Process : not null access procedure (Name : in String; Item : in Object)); private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d9af3bc5f1245f06e75687d1508f1a5e76794b6f
regtests/util-streams-files-tests.ads
regtests/util-streams-files-tests.ads
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Streams.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading and writing on a buffered stream with various buffer sizes procedure Test_Read_Write (T : in out Test); procedure Test_Write (T : in out Test); end Util.Streams.Files.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Streams.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test reading and writing on a buffered stream with various buffer sizes procedure Test_Read_Write (T : in out Test); procedure Test_Write (T : in out Test); procedure Test_Copy_Stream (T : in out Test); end Util.Streams.Files.Tests;
Declare the Test_Copy_Stream procedure
Declare the Test_Copy_Stream procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d94acfb2a6a4d37657c94819d53670605107edda
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- 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); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.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; 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); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Update to use the Probe_Manager
Update to use the Probe_Manager
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
820b8f51143d01d8f141da74b85bd3390b1758a5
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with Util.Beans.Lists.Strings; with AWA.Tags.Modules; with AWA.Services.Contexts; package body AWA.Questions.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tags" then return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Service.Load_Question (From, Id); From.Tags.Load_Tags (DB, Id); end; end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Question (Bean); Bean.Tags.Update_Tags (Bean.Get_Id); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); Object.Tags.Set_Permission ("question-edit"); return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Answer (From, From.Question, ADO.Utils.To_Identifier (Value)); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Delete_Answer (Answer => Bean); end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object is Pos : Natural; begin if Name = "tags" then Pos := From.Questions.Get_Row_Index; if Pos = 0 then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1); begin return From.Tags.Get_Tags (Item.Id); end; elsif Name = "questions" then return Util.Beans.Objects.To_Object (Value => From.Questions_Bean, Storage => Util.Beans.Objects.STATIC); else return From.Questions.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "tag" then From.Tag := Util.Beans.Objects.To_Unbounded_String (Value); From.Load_List; end if; end Set_Value; -- ------------------------------ -- Load the list of question. If a tag was set, filter the list of questions with the tag. -- ------------------------------ procedure Load_List (Into : in out Question_List_Bean) is use AWA.Questions.Models; use AWA.Services; use type ADO.Identifier; Session : ADO.Sessions.Session := Into.Service.Get_Session; Query : ADO.Queries.Context; Tag_Id : ADO.Identifier; begin AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); if Tag_Id /= ADO.NO_IDENTIFIER then Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); Query.Bind_Param (Name => "tag", Value => Tag_Id); else Query.Set_Query (AWA.Questions.Models.Query_Question_List); end if; ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Into.Questions, Session, Query); declare List : ADO.Utils.Identifier_Vector; Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; begin while Question_Info_Vectors.Has_Element (Iter) loop List.Append (Question_Info_Vectors.Element (Iter).Id); Question_Info_Vectors.Next (Iter); end loop; Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, List); end; end Load_List; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_List_Bean_Access := new Question_List_Bean; -- Session : ADO.Sessions.Session := Module.Get_Session; -- Query : ADO.Queries.Context; begin Object.Service := Module; Object.Questions_Bean := Object.Questions'Unchecked_Access; -- Query.Set_Query (AWA.Questions.Models.Query_Question_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "entity_type", -- Table => AWA.Questions.Models.QUESTION_TABLE, -- Session => Session); -- AWA.Questions.Models.List (Object.Questions, Session, Query); Object.Load_List; return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "tags" then return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Id); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); -- Load the tags if any. From.Tags.Load_Tags (Session, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; Object.Tags_Bean := Object.Tags'Access; Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE); return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Fix getting the current question identifier
Fix getting the current question identifier
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
efd1008ed1038aeefda363048b70203e23fa564e
ARM/cortex_m/src/nocache/cortex_m-cache.adb
ARM/cortex_m/src/nocache/cortex_m-cache.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of AdaCore 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 is the version used when no Data-Cache exist on the MCU package body Cortex_M.Cache is procedure Enable_I_Cache is null; procedure Enable_D_Cache is null; procedure Disable_I_Cache is null; procedure Disable_D_Cache is null; function I_Cache_Enabled return Boolean is (False); function D_Cache_Enabled return Boolean is (False); procedure Clean_DCache (Start : System.Address; Len : Natural) is null; procedure Invalidate_DCache (Start : System.Address; Len : Natural) is null; procedure Clean_Invalidate_DCache (Start : System.Address; Len : Natural) is null; end Cortex_M.Cache;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of AdaCore 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 is the version used when no Data-Cache exist on the MCU package body Cortex_M.Cache is procedure Enable_I_Cache is null; procedure Enable_D_Cache is null; procedure Disable_I_Cache is null; procedure Disable_D_Cache is null; function I_Cache_Enabled return Boolean is (False); function D_Cache_Enabled return Boolean is (False); procedure Clean_DCache (Start : System.Address; Len : Natural) is null; procedure Invalidate_DCache (Start : System.Address; Len : Natural) is null; procedure Clean_Invalidate_DCache (Start : System.Address; Len : Natural) is null; end Cortex_M.Cache;
Remove double header
Remove double header
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
d30aaba7628deee05c4eb132aef1de3a2e2d2bce
src/util-events-timers.adb
src/util-events-timers.adb
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; begin loop List.Manager.Find_Next (Timeout, Timer); exit when not Timer.Is_Scheduled; Timer.Value.Handler.Time_Handler (Timer); end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed or return the next deadline. -- ----------------------- procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin Timer.Finalize; if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Now then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is begin null; end Finalize; end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin loop Timer.Finalize; List.Manager.Find_Next (Now, Timeout, Timer); exit when not Timer.Is_Scheduled; Timer.Value.Handler.Time_Handler (Timer); end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
Implement the Finalize procedure to clear the timer list
Implement the Finalize procedure to clear the timer list
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4eff5979f329d87d37f65f891a76cf3b4702f532
matp/src/events/mat-events-targets.adb
matp/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Probe_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is ITERATE_COUNT : constant Event_Id_Type := 10_000; -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Probe_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; -- ------------------------------ -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)) is First_Event : Target_Event; Last_Event : Target_Event; First_Id : Event_Id_Type; begin Target.Get_Limits (First_Event, Last_Event); First_Id := First_Event.Id; while First_Id < Last_Event.Id loop -- Iterate over the events in groups of 10_000 to release the lock and give some -- opportunity to the server thread to add new events. Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Process); First_Id := First_Id + ITERATE_COUNT; end loop; end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
Implement the Iterate procedure to iterate over all the events
Implement the Iterate procedure to iterate over all the events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3e27ce351374c7bb56f67b647781e9a096cb99f2
mat/src/memory/mat-memory-readers.adb
mat/src/memory/mat-memory-readers.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; with MAT.Events; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- A memory allocation message is received. Register the memory -- slot in the allocated memory list. An event is posted on the -- event channel to notify the listeners that a new slot is allocated. ---------------------- procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is Inserted : Boolean; -- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Client.Data.Memory_Slots.Insert (Addr, Slot); -- Post (Client.Event_Channel, Ev); end Process_Malloc_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; if not MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. return; end if; -- Post (Client.Event_Channel, Ev); declare Slot : Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end Process_Free_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Realloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Old_Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr)); end if; if MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. -- Post (Client.Event_Channel, Ev); declare Slot : Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end if; Client.Data.Memory_Slots.Insert (Addr, Slot); end Process_Realloc_Message; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_FRAME => -- Unmarshal_Frame (Msg, Slot.Frame); null; pragma Assert (False, "must fix M_FRAME"); -- when M_TIME => -- Slot.Time := MAT.Readers.Marshaller.Get_Target_Tick (Msg.Buffer, Def.Kind); -- -- when M_THREAD => -- Slot.Thread := MAT.Readers.Marshaller.Get_Target_Thread (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (F => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); Process_Malloc_Message (For_Servant, Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Free_Message (For_Servant, Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (F => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); Process_Realloc_Message (For_Servant, Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table); procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Process_Realloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- A memory allocation message is received. Register the memory -- slot in the allocated memory list. An event is posted on the -- event channel to notify the listeners that a new slot is allocated. ---------------------- procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is Inserted : Boolean; -- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Client.Data.Memory_Slots.Insert (Addr, Slot); -- Post (Client.Event_Channel, Ev); end Process_Malloc_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; if not MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. return; end if; -- Post (Client.Event_Channel, Ev); declare Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end Process_Free_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Realloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Old_Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr)); end if; if MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. -- Post (Client.Event_Channel, Ev); declare Slot : constant Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end if; Client.Data.Memory_Slots.Insert (Addr, Slot); end Process_Realloc_Message; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr := 0; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (F => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); Process_Malloc_Message (For_Servant, Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Free_Message (For_Servant, Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Frames.Insert (F => For_Servant.Data.Frames, Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); Process_Realloc_Message (For_Servant, Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6657e91e07c1b8c7e491398e2697e98f2cb47dd3
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- 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 Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); 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 Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- 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 Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); 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 Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access); end Initialize_Filters; end AWA.Tests;
Implement Tear_Down to cleanup the users after the test execution
Implement Tear_Down to cleanup the users after the test execution
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
5d8c15f442e4a220020a8f59f16845a07ed33cfb
awa/src/awa-permissions-services.adb
awa/src/awa-permissions-services.adb
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Security.Policies.Roles; with Security.Policies.URLs; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. -- ------------------------------ function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : constant String := Util.Beans.Objects.To_String (Name); Result : Boolean; begin if Util.Beans.Objects.Is_Empty (Name) or Context = null then Result := False; elsif Util.Beans.Objects.Is_Empty (Entity) then Result := Context.Has_Permission (Perm); else declare P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm)); begin P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity)); Result := Context.Has_Permission (P); end; end if; return Util.Beans.Objects.To_Object (Result); exception when Security.Permissions.Invalid_Name => Log.Error ("Invalid permission {0}", Perm); raise; end Has_Permission; URI : aliased constant String := "http://code.google.com/p/ada-awa/auth"; -- ------------------------------ -- Register the security EL functions in the EL mapper. -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "hasPermission", Namespace => URI, Func => Has_Permission'Access, Optimize => False); end Set_Functions; -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Policies.Policy_Manager_Access; M : constant Security.Policies.Policy_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Set_Workspace_Id (Workspace); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Set_Workspace_Id (Workspace); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Workspace, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager (10); RP : constant Security.Policies.Roles.Role_Policy_Access := new Security.Policies.Roles.Role_Policy; RU : constant Security.Policies.URLs.URL_Policy_Access := new Security.Policies.URLs.URL_Policy; RE : constant Entity_Policy_Access := new Entity_Policy; begin Result.Add_Policy (RP.all'Access); Result.Add_Policy (RU.all'Access); Result.Add_Policy (RE.all'Access); Result.Set_Application (App); Log.Info ("Creation of the AWA Permissions manager"); return Result.all'Access; end Create_Permission_Manager; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Security.Policies.Roles; with Security.Policies.URLs; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. -- ------------------------------ function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : constant String := Util.Beans.Objects.To_String (Name); Result : Boolean; begin if Util.Beans.Objects.Is_Empty (Name) or Context = null then Result := False; elsif Util.Beans.Objects.Is_Empty (Entity) then Result := Context.Has_Permission (Perm); else declare P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm)); begin P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity)); Result := Context.Has_Permission (P); end; end if; return Util.Beans.Objects.To_Object (Result); exception when Security.Permissions.Invalid_Name => Log.Error ("Invalid permission {0}", Perm); raise; end Has_Permission; URI : aliased constant String := "http://code.google.com/p/ada-awa/auth"; -- ------------------------------ -- Register the security EL functions in the EL mapper. -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "hasPermission", Namespace => URI, Func => Has_Permission'Access, Optimize => False); end Set_Functions; -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Policies.Policy_Manager_Access; M : constant Security.Policies.Policy_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Set_Workspace_Id (Workspace); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Set_Workspace_Id (Workspace); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Workspace, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager (10); RP : constant Security.Policies.Roles.Role_Policy_Access := new Security.Policies.Roles.Role_Policy; RU : constant Security.Policies.URLs.URL_Policy_Access := new Security.Policies.URLs.URL_Policy; RE : constant Entity_Policy_Access := new Entity_Policy; begin Result.Add_Policy (RP.all'Access); Result.Add_Policy (RU.all'Access); Result.Add_Policy (RE.all'Access); Result.Set_Application (App); Log.Info ("Creation of the AWA Permissions manager"); return Result.all'Access; end Create_Permission_Manager; -- ------------------------------ -- Delete all the permissions for a user and on the given workspace. -- ------------------------------ procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (Models.PERMISSION_TABLE); Result : Natural; begin Stmt.Set_Filter (Filter => "workspace_id = ? AND user_id = ?"); Stmt.Add_Param (Value => Workspace); Stmt.Add_Param (Value => User); Stmt.Execute (Result); Log.Info ("Deleted {0} permissions for user {1} in workspace {2}", Natural'Image (Result), ADO.Identifier'Image (User), ADO.Identifier'Image (Workspace)); end Delete_Permissions; end AWA.Permissions.Services;
Implement the Delete_Permissions procedure to remove all the permissions for a user in a given workspace
Implement the Delete_Permissions procedure to remove all the permissions for a user in a given workspace
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ee3743de6922a33a391760c2b761ad62ad797f9b
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); 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.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;
Configure the exception message for the AWA.Permissions.NO_PERMISSION exception
Configure the exception message for the AWA.Permissions.NO_PERMISSION exception
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6ca0168425db62899d768f46be5c2f989e5d5584
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 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) 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; Related : in MAT.Events.Targets.Target_Event_Vector) return String; end MAT.Formats;
Declare the Duration function to format a duration in sec, msec, usec
Declare the Duration function to format a duration in sec, msec, usec
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a98380050fcdb192378de83f2f27ed382f9b120c
src/ado-parameters.ads
src/ado-parameters.ads
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- == Query Parameters == -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- == Query Parameters == -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_LONG_FLOAT, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_LONG_FLOAT => Float : Long_Float; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Float); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
Add T_LONG_FLOAT enumeration and a Bind_Param with a Long_Float
Add T_LONG_FLOAT enumeration and a Bind_Param with a Long_Float
Ada
apache-2.0
stcarrez/ada-ado
74e8118a621b2f0a19c86640cb582a141e32f874
regtests/wiki-filters-html-tests.adb
regtests/wiki-filters-html-tests.adb
----------------------------------------------------------------------- -- wiki-filters-html-tests -- Unit tests for wiki HTML filters -- 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.Test_Caller; with Util.Assertions; with Util.Strings; with Util.Log.Loggers; package body Wiki.Filters.Html.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters"); package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Tag); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag", Test_Find_Tag'Access); end Add_Tests; -- ------------------------------ -- Test Find_Tag operation. -- ------------------------------ procedure Test_Find_Tag (T : in out Test) is begin for I in Html_Tag'Range loop declare Name : constant String := Html_Tag'Image (I); Wname : constant Wide_Wide_String := Html_Tag'Wide_Wide_Image (I); Pos : constant Natural := Util.Strings.Index (Name, '_'); Tag : constant Html_Tag := Find_Tag (Wname (Wname'First .. Pos - 1)); begin Log.Info ("Checking tag {0}", Name); if I /= ROOT_HTML_TAG then Assert_Equals (T, I, Tag, "Find_Tag failed"); end if; Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Wname (Wname'First .. Pos - 1) & "x"), "Find_Tag must return UNKNOWN_TAG"); end; end loop; end Test_Find_Tag; end Wiki.Filters.Html.Tests;
----------------------------------------------------------------------- -- wiki-filters-html-tests -- Unit tests for wiki HTML filters -- 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.Test_Caller; with Util.Assertions; with Util.Strings; with Util.Log.Loggers; package body Wiki.Filters.Html.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Wiki.Filters"); package Caller is new Util.Test_Caller (Test, "Wikis.Filters.Html"); procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Html_Tag); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Filters.Html.Find_Tag", Test_Find_Tag'Access); end Add_Tests; -- ------------------------------ -- Test Find_Tag operation. -- ------------------------------ procedure Test_Find_Tag (T : in out Test) is begin for I in Html_Tag'Range loop declare Name : constant String := Html_Tag'Image (I); Wname : constant Wide_Wide_String := Html_Tag'Wide_Wide_Image (I); Pos : constant Natural := Util.Strings.Index (Name, '_'); Tname : constant Wide_Wide_String := Wname (Wname'First .. Pos - 1); Tag : constant Html_Tag := Find_Tag (Tname); begin Log.Info ("Checking tag {0}", Name); if I /= ROOT_HTML_TAG then Assert_Equals (T, I, Tag, "Find_Tag failed"); end if; Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Tname & "x"), "Find_Tag must return UNKNOWN_TAG"); for K in Tname'Range loop if K = Tname'First then Assert_Equals (T, UNKNOWN_TAG, Find_Tag ("_" & Tname (Tname'First + 1 .. Tname'Last)), "Find_Tag must return UNKNOWN_TAG"); elsif K = Tname'Last then Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Tname (Tname'First .. K - 1) & "_"), "Find_Tag must return UNKNOWN_TAG"); else Assert_Equals (T, UNKNOWN_TAG, Find_Tag (Tname (Tname'First .. K - 1) & "_" & Tname (K + 1 .. Tname'Last)), "Find_Tag must return UNKNOWN_TAG"); end if; end loop; end; end loop; end Test_Find_Tag; end Wiki.Filters.Html.Tests;
Add more tests for Find_Tag operation
Add more tests for Find_Tag operation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4df97a12852dfbce6b3d8c90cbf66195871f5423
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 begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_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)); 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 begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); 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; -- ------------------------------ -- 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 begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_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 begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); 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;
Implement Is_Using_TOC and emit the N_TOC_DISPLAY node
Implement Is_Using_TOC and emit the N_TOC_DISPLAY node
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f4735498cf77e7aa748d0fd4c4bc49e64c5eedf3
src/asf-components-widgets-likes.ads
src/asf-components-widgets-likes.ads
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Twitter like generator -- ------------------------------ type Twitter_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Applications; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- The application configuration parameter that defines which Facebook client ID must be used. package P_Facebook_App_Id is new ASF.Applications.Parameter ("facebook.client_id", ""); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Twitter like generator -- ------------------------------ type Twitter_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
Declare the P_Facebook_App_Id application configuration parameter
Declare the P_Facebook_App_Id application configuration parameter
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1187519a9089b9b22e87a7c59609f2589e5ff694
awa/src/awa-users-beans.adb
awa/src/awa-users-beans.adb
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user 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; with ASF.Principals; with ASF.Sessions; with ASF.Events.Faces.Actions; with ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Cookies; with ASF.Applications.Messages.Factory; with ASF.Security.Filters; with AWA.Services.Contexts; package body AWA.Users.Beans is use Util.Log; use AWA.Users.Models; use ASF.Applications; Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans"); -- Helper to send a remove cookie in the current response procedure Remove_Cookie (Name : in String); -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_signup_sent", Messages.INFO); exception when Services.User_Exist => Outcome := To_Unbounded_String ("failure"); Messages.Factory.Add_Message (Ctx.all, "users.signup_error_message"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Principal : AWA.Users.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), IpAddr => "", Principal => Principal); Data.Set_Session_Principal (Principal); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_registration_done", Messages.INFO); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); Messages.Factory.Add_Message (Ctx.all, "users.error_verify_register_key"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_lost_password_sent", Messages.INFO); exception when Services.Not_Found => Messages.Factory.Add_Message (Ctx.all, "users.error_email_not_found"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; Principal : AWA.Users.Principals.Principal_Access; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", Principal => Principal); Data.Set_Session_Principal (Principal); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_reset_password_done", Messages.INFO); exception when Services.Not_Found => Messages.Factory.Add_Message (Ctx.all, "users.error_reset_password"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access) is pragma Unreferenced (Data); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access) is Cookie : constant String := Data.Manager.Get_Authenticate_Cookie (Principal.Get_Session_Identifier); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Ctx.Get_Response.Add_Cookie (Cookie => C); end Set_Authenticate_Cookie; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Principal : AWA.Users.Principals.Principal_Access; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", Principal => Principal); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (Principal); Data.Set_Authenticate_Cookie (Principal); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message"); end Authenticate_User; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout the user and closes the session. -- ------------------------------ procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is use type ASF.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False); begin Outcome := To_Unbounded_String ("success"); -- If there is no session, we are done. if not Session.Is_Valid then return; end if; declare Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal; begin if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then declare P : constant AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Principal'Class (Principal.all)'Access; begin Data.Manager.Close_Session (Id => P.Get_Session_Identifier, Logout => True); exception when others => Log.Error ("Exception when closing user session..."); end; end if; Session.Invalidate; end; -- Remove the session cookie. Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Remove_Cookie (ASF.Security.Filters.AID_COOKIE); end Logout_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Modules.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Logout_User, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access, Logout_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = EMAIL_ATTR then return Util.Beans.Objects.To_Object (From.Email); elsif Name = PASSWORD_ATTR then return Util.Beans.Objects.To_Object (From.Password); elsif Name = FIRST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.First_Name); elsif Name = LAST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.Last_Name); elsif Name = KEY_ATTR then return Util.Beans.Objects.To_Object (From.Access_Key); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = EMAIL_ATTR then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = PASSWORD_ATTR then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = FIRST_NAME_ATTR then From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = LAST_NAME_ATTR then From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = KEY_ATTR then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Get the value identified by the name. The following names are recognized: -- o isLogged Boolean True if a user is logged -- o name String The user name -- o email String The user email address -- o id Long The user identifier -- ------------------------------ overriding function Get_Value (From : in Current_User_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); 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 if Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (False); else return Util.Beans.Objects.Null_Object; end if; else declare User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; begin if User.Is_Null then if Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (False); else return Util.Beans.Objects.Null_Object; end if; else if Name = USER_NAME_ATTR then return Util.Beans.Objects.To_Object (String '(User.Get_Name)); elsif Name = USER_EMAIL_ATTR then return Util.Beans.Objects.To_Object (String '(User.Get_Email.Get_Email)); elsif Name = USER_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (User.Get_Id)); elsif Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (True); else return Util.Beans.Objects.Null_Object; end if; end if; end; end if; end Get_Value; -- ------------------------------ -- Create the current user bean. -- ------------------------------ function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Current_User_Bean_Access := new Current_User_Bean; begin return Object.all'Access; end Create_Current_User_Bean; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user 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; with ASF.Principals; with ASF.Sessions; with ASF.Events.Faces.Actions; with ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Cookies; with ASF.Applications.Messages.Factory; with ASF.Security.Filters; with ADO.Sessions; with AWA.Services.Contexts; package body AWA.Users.Beans is use Util.Log; use AWA.Users.Models; use ASF.Applications; Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans"); -- Helper to send a remove cookie in the current response procedure Remove_Cookie (Name : in String); -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_signup_sent", Messages.INFO); exception when Services.User_Exist => Outcome := To_Unbounded_String ("failure"); Messages.Factory.Add_Message (Ctx.all, "users.signup_error_message"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Principal : AWA.Users.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), IpAddr => "", Principal => Principal); Data.Set_Session_Principal (Principal); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_registration_done", Messages.INFO); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); Messages.Factory.Add_Message (Ctx.all, "users.error_verify_register_key"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_lost_password_sent", Messages.INFO); exception when Services.Not_Found => Messages.Factory.Add_Message (Ctx.all, "users.error_email_not_found"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; Principal : AWA.Users.Principals.Principal_Access; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", Principal => Principal); Data.Set_Session_Principal (Principal); Outcome := To_Unbounded_String ("success"); -- Add a message to the flash context so that it will be displayed on the next page. Flash.Set_Keep_Messages (True); Messages.Factory.Add_Message (Ctx.all, "users.message_reset_password_done", Messages.INFO); exception when Services.Not_Found => Messages.Factory.Add_Message (Ctx.all, "users.error_reset_password"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access) is pragma Unreferenced (Data); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access) is Cookie : constant String := Data.Manager.Get_Authenticate_Cookie (Principal.Get_Session_Identifier); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Ctx.Get_Response.Add_Cookie (Cookie => C); end Set_Authenticate_Cookie; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is Principal : AWA.Users.Principals.Principal_Access; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", Principal => Principal); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (Principal); Data.Set_Authenticate_Cookie (Principal); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message"); end Authenticate_User; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout the user and closes the session. -- ------------------------------ procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is use type ASF.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False); begin Outcome := To_Unbounded_String ("success"); -- If there is no session, we are done. if not Session.Is_Valid then return; end if; declare Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal; begin if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then declare P : constant AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Principal'Class (Principal.all)'Access; begin Data.Manager.Close_Session (Id => P.Get_Session_Identifier, Logout => True); exception when others => Log.Error ("Exception when closing user session..."); end; end if; Session.Invalidate; end; -- Remove the session cookie. Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Remove_Cookie (ASF.Security.Filters.AID_COOKIE); end Logout_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Modules.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Logout_User, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access, Logout_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = EMAIL_ATTR then return Util.Beans.Objects.To_Object (From.Email); elsif Name = PASSWORD_ATTR then return Util.Beans.Objects.To_Object (From.Password); elsif Name = FIRST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.First_Name); elsif Name = LAST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.Last_Name); elsif Name = KEY_ATTR then return Util.Beans.Objects.To_Object (From.Access_Key); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = EMAIL_ATTR then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = PASSWORD_ATTR then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = FIRST_NAME_ATTR then From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = LAST_NAME_ATTR then From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = KEY_ATTR then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Get the value identified by the name. The following names are recognized: -- o isLogged Boolean True if a user is logged -- o name String The user name -- o email String The user email address -- o id Long The user identifier -- ------------------------------ overriding function Get_Value (From : in Current_User_Bean; Name : in String) return Util.Beans.Objects.Object is package ASC renames AWA.Services.Contexts; pragma Unreferenced (From); use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin if Ctx = null then if Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (False); else return Util.Beans.Objects.Null_Object; end if; else declare User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; begin if User.Is_Null then if Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (False); else return Util.Beans.Objects.Null_Object; end if; else if Name = USER_NAME_ATTR then return Util.Beans.Objects.To_Object (String '(User.Get_Name)); elsif Name = USER_EMAIL_ATTR then declare Email : AWA.Users.Models.Email_Ref'Class := User.Get_Email; begin if not Email.Is_Loaded then -- The email object was not loaded. Load it using a new database session. declare Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); begin Email.Load (Session, Email.Get_Id); end; end if; return Util.Beans.Objects.To_Object (String '(Email.Get_Email)); end; elsif Name = USER_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (User.Get_Id)); elsif Name = IS_LOGGED_ATTR then return Util.Beans.Objects.To_Object (True); else return Util.Beans.Objects.Null_Object; end if; end if; end; end if; end Get_Value; -- ------------------------------ -- Create the current user bean. -- ------------------------------ function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Current_User_Bean_Access := new Current_User_Bean; begin return Object.all'Access; end Create_Current_User_Bean; end AWA.Users.Beans;
Fix retrieval of user email address
Fix retrieval of user email address
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
4ca4512266e13af27b42c8f56195126e10a3dda4
src/mysql/ado-mysql.ads
src/mysql/ado-mysql.ads
----------------------------------------------------------------------- -- ado-mysql -- MySQL Database Drivers -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- === MySQL Database Driver === -- The MySQL database driver can be initialize explicitly by using the `ado_mysql` -- GNAT project and calling the initialization procedure. -- -- ADO.Mysql.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "mysql:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Mysql.Initialize (Config); -- package ADO.Mysql is -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); end ADO.Mysql;
----------------------------------------------------------------------- -- ado-mysql -- MySQL Database Drivers -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- === MySQL Database Driver === -- The MySQL database driver can be initialize explicitly by using the `ado_mysql` -- GNAT project and calling the initialization procedure. -- -- ADO.Mysql.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "mysql://localhost:3306/ado_test"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Mysql.Initialize (Config); -- -- The MySQL database driver supports the following properties: -- -- | Name | Description | -- | ----------- | --------- | -- | user | The user name to connect to the server | -- | password | The user password to connect to the server | -- | socket | The optional Unix socket path for a Unix socket base connection | -- | encoding | The encoding to be used for the connection (ex: UTF-8) | -- package ADO.Mysql is -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); end ADO.Mysql;
Update the documentation for the MySQL database driver
Update the documentation for the MySQL database driver
Ada
apache-2.0
stcarrez/ada-ado
8b2d4a837b9804f6a97f091c9580c6f19d5d9d00
mat/regtests/mat-testsuite.adb
mat/regtests/mat-testsuite.adb
----------------------------------------------------------------------- -- mat-testsuite - MAT Testsuite -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Readers.Tests; package body MAT.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin MAT.Readers.Tests.Add_Tests (Result); return Result; end Suite; end MAT.Testsuite;
----------------------------------------------------------------------- -- mat-testsuite - MAT Testsuite -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Readers.Tests; with MAT.Targets.Tests; package body MAT.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin MAT.Readers.Tests.Add_Tests (Result); MAT.Targets.Tests.Add_Tests (Result); return Result; end Suite; end MAT.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d166dd7ec5d7260ab790f07325a3d36db41b636c
src/sqlite/ado-schemas-sqlite.adb
src/sqlite/ado-schemas-sqlite.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First < 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value , ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); Col.Collation := Stmt.Get_Unbounded_String (2); Col.Default := Stmt.Get_Unbounded_String (5); if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); declare Type_Name : constant String := Util.Strings.Transforms.To_Lower_Case (To_String (Value)); begin Col.Col_Type := String_To_Type (Type_Name); Col.Size := String_To_Length (Type_Name); end; Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First = 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value, ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); Col.Collation := Stmt.Get_Unbounded_String (2); Col.Default := Stmt.Get_Unbounded_String (5); if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); declare Type_Name : constant String := Util.Strings.Transforms.To_Lower_Case (To_String (Value)); begin Col.Col_Type := String_To_Type (Type_Name); Col.Size := String_To_Length (Type_Name); end; Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
a37c0e61f164240353dd7698959ef223693378e6
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- OpenID 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.Auth; -- == OpenID == -- The <b>Security.OpenID</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Security.OpenID.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.OpenID.End_Point; -- Assoc : constant Security.OpenID.Association_Access := new Security.OpenID.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : OpenID.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Auth); -- if Security.OpenID.Get_Status (Auth) = Security.OpenID.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth); -- package Security.OpenID is pragma Obsolescent ("Use the Security.Auth package instead"); Invalid_End_Point : exception; Service_Error : exception; subtype Parameters is Security.Auth.Parameters; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. subtype End_Point is Security.Auth.End_Point; -- ------------------------------ -- 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. subtype Association is Security.Auth.End_Point; subtype Auth_Result is Security.Auth.Auth_Result; -- ------------------------------ -- OpenID provider -- ------------------------------ -- subtype Authentication is Security.Auth.Authentication; -- ------------------------------ -- OpenID Default principal -- ------------------------------ subtype Principal is Security.Auth.Principal; subtype Principal_Access is Security.Auth.Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. subtype Manager is Security.Auth.Manager; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); private use Ada.Strings.Unbounded; -- -- type Manager is new Ada.Finalization.Limited_Controlled with record -- Realm : Unbounded_String; -- Return_To : Unbounded_String; -- end record; end Security.OpenID;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- 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 Security.Auth; -- == OpenID == -- The <b>Security.OpenID</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Security.OpenID.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.OpenID.End_Point; -- Assoc : constant Security.OpenID.Association_Access := new Security.OpenID.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : OpenID.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Auth); -- if Security.OpenID.Get_Status (Auth) = Security.OpenID.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth); -- package Security.OpenID is pragma Obsolescent ("Use the Security.Auth package instead"); Invalid_End_Point : exception; Service_Error : exception; subtype Parameters is Security.Auth.Parameters; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. subtype End_Point is Security.Auth.End_Point; -- ------------------------------ -- 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. subtype Association is Security.Auth.End_Point; subtype Auth_Result is Security.Auth.Auth_Result; -- ------------------------------ -- OpenID provider -- ------------------------------ -- subtype Authentication is Security.Auth.Authentication; -- ------------------------------ -- OpenID Default principal -- ------------------------------ subtype Principal is Security.Auth.Principal; subtype Principal_Access is Security.Auth.Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. subtype Manager is Security.Auth.Manager; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); end Security.OpenID;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-security
b6fa618efdea47e4a33a3fed346885d99922bea5
src/orka/implementation/orka-resources-textures-ktx.adb
src/orka/implementation/orka-resources-textures-ktx.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.Exceptions; with Ada.Real_Time; with GL.Debug; with GL.Low_Level.Enums; with GL.Pixels; with GL.Types; with Orka.KTX; with Orka.Resources.Locations; package body Orka.Resources.Textures.KTX is package Debug_Messages is new GL.Debug.Messages (GL.Debug.Third_Party, GL.Debug.Other); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)); ----------------------------------------------------------------------------- overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)) is Bytes : Byte_Array_Access renames Object.Data.Bytes; Path : String renames SU.To_String (Object.Data.Path); T1 : Ada.Real_Time.Time renames Object.Data.Start_Time; T2 : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Resource : constant Texture_Ptr := new Texture'(others => <>); begin T3 := Ada.Real_Time.Clock; -- Allocate storage case Header.Kind is when Texture_3D | Texture_2D_Array | Texture_Cube_Map_Array => declare Texture : GL.Objects.Textures.Texture_3D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width, Header.Height, Header.Depth); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width, Header.Height, Header.Depth); end if; Resource.Texture.Replace_Element (Texture); end; when Texture_2D | Texture_1D_Array | Texture_Cube_Map => declare Texture : GL.Objects.Textures.Texture_2D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width, Header.Height); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width, Header.Height); end if; Resource.Texture.Replace_Element (Texture); end; when Texture_1D => declare Texture : GL.Objects.Textures.Texture_1D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width); end if; Resource.Texture.Replace_Element (Texture); end; when others => raise Program_Error; end case; T4 := Ada.Real_Time.Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); package Textures renames GL.Objects.Textures; begin for Level in 0 .. Levels - 1 loop declare Image_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); Padding_Size : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Padding_Size; Image_Data : aliased Byte_Array := Bytes (Image_Size_Index + 4 .. Image_Size_Index + 4 + Stream_Element_Offset (Image_Size) - 1); procedure Load_1D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_1D renames Textures.Texture_1D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, Header.Width, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); else Texture.Load_From_Data (Level, 0, Header.Width, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_1D; procedure Load_2D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_2D renames Textures.Texture_2D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, 0, Header.Width, Header.Height, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); else Texture.Load_From_Data (Level, 0, 0, Header.Width, Header.Height, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_2D; procedure Load_3D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_3D renames Textures.Texture_3D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, 0, 0, Header.Width, Header.Height, Header.Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); -- TODO For Texture_Cube_Map, Image_Size is the size of one face else Texture.Load_From_Data (Level, 0, 0, 0, Header.Width, Header.Height, Header.Depth, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_3D; begin case Header.Kind is when Texture_3D | Texture_2D_Array | Texture_Cube_Map_Array => Resource.Texture.Query_Element (Load_3D'Access); when Texture_2D | Texture_1D_Array | Texture_Cube_Map => Resource.Texture.Query_Element (Load_2D'Access); when Texture_1D => Resource.Texture.Query_Element (Load_1D'Access); when others => raise Program_Error; end case; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Ada.Real_Time.Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Resource.Texture.Element.Generate_Mipmap; end if; T6 := Ada.Real_Time.Clock; -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); declare use type Ada.Real_Time.Time; Reading_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); Parsing_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T3 - T2); Storage_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T4 - T3); Buffers_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T5 - T4); Mipmap_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T6 - T5); Loading_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T6 - T1); begin Debug_Messages.Insert (GL.Debug.Notification, "Loaded texture " & Path); Debug_Messages.Insert (GL.Debug.Notification, " width:" & GL.Types.Size'Image (Header.Width) & " height:" & GL.Types.Size'Image (Header.Height) & " depth:" & GL.Types.Size'Image (Header.Depth) & " array length:" & GL.Types.Size'Image (Header.Array_Elements) & " mipmap levels:" & GL.Types.Size'Image (Levels)); if Header.Compressed then Debug_Messages.Insert (GL.Debug.Notification, " compressed format: " & GL.Pixels.Compressed_Format'Image (Header.Compressed_Format)); else Debug_Messages.Insert (GL.Debug.Notification, " internal: " & GL.Pixels.Internal_Format'Image (Header.Internal_Format)); Debug_Messages.Insert (GL.Debug.Notification, " format: " & GL.Pixels.Format'Image (Header.Format)); Debug_Messages.Insert (GL.Debug.Notification, " format: " & GL.Pixels.Data_Type'Image (Header.Data_Type)); end if; Debug_Messages.Insert (GL.Debug.Notification, " loaded in" & Duration'Image (Loading_Time) & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " reading file:" & Duration'Image (Reading_Time) & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " parsing header:" & Duration'Image (Parsing_Time) & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " storage:" & Duration'Image (Storage_Time) & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " buffers:" & Duration'Image (Buffers_Time) & " ms"); if Header.Mipmap_Levels = 0 then Debug_Messages.Insert (GL.Debug.Notification, " generating mipmap:" & Duration'Image (Mipmap_Time) & " ms"); end if; end; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); end Orka.Resources.Textures.KTX;
-- 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.Exceptions; with Ada.Real_Time; with GL.Debug; with GL.Low_Level.Enums; with GL.Pixels; with GL.Types; with Orka.KTX; with Orka.Resources.Locations; package body Orka.Resources.Textures.KTX is package Debug_Messages is new GL.Debug.Messages (GL.Debug.Third_Party, GL.Debug.Other); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)); ----------------------------------------------------------------------------- overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)) is Bytes : Byte_Array_Access renames Object.Data.Bytes; Path : String renames SU.To_String (Object.Data.Path); T1 : Ada.Real_Time.Time renames Object.Data.Start_Time; T2 : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Resource : constant Texture_Ptr := new Texture'(others => <>); begin T3 := Ada.Real_Time.Clock; -- Allocate storage case Header.Kind is when Texture_3D | Texture_2D_Array | Texture_Cube_Map_Array => declare Texture : GL.Objects.Textures.Texture_3D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width, Header.Height, Header.Depth); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width, Header.Height, Header.Depth); end if; Resource.Texture.Replace_Element (Texture); end; when Texture_2D | Texture_1D_Array | Texture_Cube_Map => declare Texture : GL.Objects.Textures.Texture_2D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width, Header.Height); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width, Header.Height); end if; Resource.Texture.Replace_Element (Texture); end; when Texture_1D => declare Texture : GL.Objects.Textures.Texture_1D (Header.Kind); begin if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Header.Width); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Header.Width); end if; Resource.Texture.Replace_Element (Texture); end; when others => raise Program_Error; end case; T4 := Ada.Real_Time.Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); package Textures renames GL.Objects.Textures; begin for Level in 0 .. Levels - 1 loop declare Image_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); Padding_Size : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Padding_Size; Image_Data : aliased Byte_Array := Bytes (Image_Size_Index + 4 .. Image_Size_Index + 4 + Stream_Element_Offset (Image_Size) - 1); procedure Load_1D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_1D renames Textures.Texture_1D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, Header.Width, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); else Texture.Load_From_Data (Level, 0, Header.Width, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_1D; procedure Load_2D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_2D renames Textures.Texture_2D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, 0, Header.Width, Header.Height, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); else Texture.Load_From_Data (Level, 0, 0, Header.Width, Header.Height, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_2D; procedure Load_3D (Element : Textures.Texture_Base'Class) is Texture : Textures.Texture_3D renames Textures.Texture_3D (Element); begin if Header.Compressed then Texture.Load_From_Compressed_Data (Level, 0, 0, 0, Header.Width, Header.Height, Header.Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data'Address); -- TODO For Texture_Cube_Map, Image_Size is the size of one face else Texture.Load_From_Data (Level, 0, 0, 0, Header.Width, Header.Height, Header.Depth, Header.Format, Header.Data_Type, Image_Data'Address); end if; end Load_3D; begin case Header.Kind is when Texture_3D | Texture_2D_Array | Texture_Cube_Map_Array => Resource.Texture.Query_Element (Load_3D'Access); when Texture_2D | Texture_1D_Array | Texture_Cube_Map => Resource.Texture.Query_Element (Load_2D'Access); when Texture_1D => Resource.Texture.Query_Element (Load_1D'Access); when others => raise Program_Error; end case; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Ada.Real_Time.Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Resource.Texture.Element.Generate_Mipmap; end if; T6 := Ada.Real_Time.Clock; -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); declare use type Ada.Real_Time.Time; Reading_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); Parsing_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T3 - T2); Storage_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T4 - T3); Buffers_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T5 - T4); Mipmap_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T6 - T5); Loading_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T6 - T1); begin Debug_Messages.Insert (GL.Debug.Notification, "Loaded texture " & Path); Debug_Messages.Insert (GL.Debug.Notification, " width:" & Header.Width'Image & " height:" & Header.Height'Image & " depth:" & Header.Depth'Image & " array length:" & Header.Array_Elements'Image & " mipmap levels:" & Levels'Image); if Header.Compressed then Debug_Messages.Insert (GL.Debug.Notification, " compressed format: " & Header.Compressed_Format'Image); else Debug_Messages.Insert (GL.Debug.Notification, " internal: " & Header.Internal_Format'Image); Debug_Messages.Insert (GL.Debug.Notification, " format: " & Header.Format'Image); Debug_Messages.Insert (GL.Debug.Notification, " format: " & Header.Data_Type'Image); end if; Debug_Messages.Insert (GL.Debug.Notification, " loaded in" & Loading_Time'Image & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " reading file:" & Reading_Time'Image & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " parsing header:" & Parsing_Time'Image & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " storage:" & Storage_Time'Image & " ms"); Debug_Messages.Insert (GL.Debug.Notification, " buffers:" & Buffers_Time'Image & " ms"); if Header.Mipmap_Levels = 0 then Debug_Messages.Insert (GL.Debug.Notification, " generating mipmap:" & Mipmap_Time'Image & " ms"); end if; end; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); end Orka.Resources.Textures.KTX;
Use V'Image instead of T'Image (V) in Orka.Resources.Textures.KTX
orka: Use V'Image instead of T'Image (V) in Orka.Resources.Textures.KTX Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
c6d90eede7fc8e46fbdcc92843ba182e28ee5037
src/security-openid.adb
src/security-openid.adb
----------------------------------------------------------------------- -- security-openid -- OpenID 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.Fixed; with Ada.Text_IO; with Util.Http.Clients; with Util.Strings; with Util.Encoders; with Util.Log.Loggers; with Util.Encoders.SHA1; with Util.Encoders.HMAC.SHA1; package body Security.OpenID is use Ada.Strings.Fixed; use Util.Log; Log : constant Util.Log.Loggers.Logger := Loggers.Create ("Security.OpenID"); -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String) is begin null; end Initialize; end Security.OpenID;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- 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. ----------------------------------------------------------------------- package body Security.OpenID is -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String) is begin null; end Initialize; end Security.OpenID;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-security
3a3163e8695d57a1524817e531451845881d4ab4
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * Discovery to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * Verify to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
13879b0d1216840e4b83d5fbeb131672ef3d7f27
matp/src/events/mat-events-targets.adb
matp/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Events.Targets is ITERATE_COUNT : constant Event_Id_Type := 10_000; -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; -- ------------------------------ -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)) is First_Event : Target_Event; Last_Event : Target_Event; First_Id : Event_Id_Type; begin Target.Get_Limits (First_Event, Last_Event); First_Id := First_Event.Id; while First_Id < Last_Event.Id loop -- Iterate over the events in groups of 10_000 to release the lock and give some -- opportunity to the server thread to add new events. Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Process); First_Id := First_Id + ITERATE_COUNT; end loop; end Iterate; -- ------------------------------ -- Release the storage allocated for the events. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Events) is begin Target.Events.Clear; end Finalize; protected body Event_Collector is procedure Update (Id : in Event_Id_Type; Process : not null access procedure (Event : in out Probe_Event_Type)); -- ------------------------------ -- Internal operation to update the event represented by <tt>Id</tt>. -- ------------------------------ procedure Update (Id : in Event_Id_Type; Process : not null access procedure (Event : in out Probe_Event_Type)) is Iter : constant Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin if Event_Id_Maps.Has_Element (Iter) then Block := Event_Id_Maps.Element (Iter); Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then Process (Block.Events (Pos)); end if; end if; end Update; -- ------------------------------ -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. -- ------------------------------ procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type) is procedure Update_Size (Event : in out Probe_Event_Type); procedure Update_Next (Event : in out Probe_Event_Type); procedure Update_Size (Event : in out Probe_Event_Type) is begin Event.Size := Size; Event.Prev_Id := Prev_Id; end Update_Size; procedure Update_Next (Event : in out Probe_Event_Type) is begin Event.Next_Id := Id; end Update_Next; begin Update (Id, Update_Size'Access); Update (Prev_Id, Update_Next'Access); end Update_Event; -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; -- ------------------------------ -- Clear the events. -- ------------------------------ procedure Clear is procedure Free is new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access); begin while not Events.Is_Empty loop declare Block : Event_Block_Access := Events.First_Element; begin Free (Block); Events.Delete_First; end; end loop; Current := null; Last_Id := 0; Ids.Clear; end Clear; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Events.Targets is ITERATE_COUNT : constant Event_Id_Type := 10_000; -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- Update the event instance to allocate the event Id. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in out Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; -- ------------------------------ -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)) is First_Event : Target_Event; Last_Event : Target_Event; First_Id : Event_Id_Type; begin Target.Get_Limits (First_Event, Last_Event); First_Id := First_Event.Id; while First_Id < Last_Event.Id loop -- Iterate over the events in groups of 10_000 to release the lock and give some -- opportunity to the server thread to add new events. Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Process); First_Id := First_Id + ITERATE_COUNT; end loop; end Iterate; -- ------------------------------ -- Release the storage allocated for the events. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Events) is begin Target.Events.Clear; end Finalize; protected body Event_Collector is procedure Update (Id : in Event_Id_Type; Process : not null access procedure (Event : in out Probe_Event_Type)); -- ------------------------------ -- Internal operation to update the event represented by <tt>Id</tt>. -- ------------------------------ procedure Update (Id : in Event_Id_Type; Process : not null access procedure (Event : in out Probe_Event_Type)) is Iter : constant Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin if Event_Id_Maps.Has_Element (Iter) then Block := Event_Id_Maps.Element (Iter); Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then Process (Block.Events (Pos)); end if; end if; end Update; -- ------------------------------ -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. -- ------------------------------ procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type) is procedure Update_Size (Event : in out Probe_Event_Type); procedure Update_Next (Event : in out Probe_Event_Type); procedure Update_Size (Event : in out Probe_Event_Type) is begin Event.Size := Size; Event.Prev_Id := Prev_Id; end Update_Size; procedure Update_Next (Event : in out Probe_Event_Type) is begin Event.Next_Id := Id; end Update_Next; begin Update (Id, Update_Size'Access); Update (Prev_Id, Update_Next'Access); end Update_Event; -- ------------------------------ -- Add the event in the list of events. -- Update the event instance to allocate the event Id. -- ------------------------------ procedure Insert (Event : in out Probe_Event_Type) is begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; -- ------------------------------ -- Clear the events. -- ------------------------------ procedure Clear is procedure Free is new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access); begin while not Events.Is_Empty loop declare Block : Event_Block_Access := Events.First_Element; begin Free (Block); Events.Delete_First; end; end loop; Current := null; Last_Id := 0; Ids.Clear; end Clear; end Event_Collector; end MAT.Events.Targets;
Change the Insert procedure to update the Event.Id after the insertion
Change the Insert procedure to update the Event.Id after the insertion
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4a266c7ec1d8ec957c96641966e3d52f77a5fa44
regtests/util-http-clients-tests.ads
regtests/util-http-clients-tests.ads
----------------------------------------------------------------------- -- 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.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; end record; type Test_Server_Access is access all Test_Server'Class; -- 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); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; end record; type Test_Server_Access is access all Test_Server'Class; -- 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); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
Declare Test_Http_Put and Test_Http_Delete
Declare Test_Http_Put and Test_Http_Delete
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e8e70e8a883a9c8313caec9fb2d0455e98d03868
src/http/curl/util-http-clients-curl.adb
src/http/curl/util-http-clients-curl.adb
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Util.Http.Clients.Curl.Constants; package body Util.Http.Clients.Curl is use System; pragma Linker_Options ("-lcurl"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl"); function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access; PUT_TOKEN : Chars_Ptr := Strings.New_String ("PUT"); Manager : aliased Curl_Http_Manager; -- ------------------------------ -- Register the CURL Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. -- ------------------------------ procedure Check_Code (Code : in CURL_Code; Message : in String) is begin if Code /= CURLE_OK then declare Error : constant Chars_Ptr := Curl_Easy_Strerror (Code); Msg : constant String := Interfaces.C.Strings.Value (Error); begin Log.Error ("{0}: {1}", Message, Msg); raise Connection_Error with Msg; end; end if; end Check_Code; -- ------------------------------ -- Create a new HTTP request associated with the current request manager. -- ------------------------------ procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); Request : Curl_Http_Request_Access; Data : CURL; begin Data := Curl_Easy_Init; if Data = System.Null_Address then raise Storage_Error with "curl_easy_init cannot create the CURL instance"; end if; Request := new Curl_Http_Request; Request.Data := Data; Http.Delegate := Request.all'Access; end Create; function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is begin return Curl_Http_Request'Class (Http.Delegate.all)'Access; end Get_Request; -- ------------------------------ -- This function is called by CURL when a response line was read. -- ------------------------------ function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T is Total : constant Size_T := Size * Nmemb; Line : constant String := Interfaces.C.Strings.Value (Data, Total); begin Log.Info ("RCV: {0}", Line); if Response.Parsing_Body then Ada.Strings.Unbounded.Append (Response.Content, Line); elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then Response.Parsing_Body := True; else declare Pos : constant Natural := Util.Strings.Index (Line, ':'); Start : Natural; Last : Natural; begin if Pos > 0 then Start := Pos + 1; while Start <= Line'Last and Line (Start) = ' ' loop Start := Start + 1; end loop; Last := Line'Last; while Last >= Start and (Line (Last) = ASCII.CR or Line (Last) = ASCII.LF) loop Last := Last - 1; end loop; Response.Add_Header (Name => Line (Line'First .. Pos - 1), Value => Line (Start .. Last)); end if; end; end if; return Total; end Read_Response; -- ------------------------------ -- Prepare to setup the headers in the request. -- ------------------------------ procedure Set_Headers (Request : in out Curl_Http_Request) is procedure Process (Name, Value : in String) is S : Chars_Ptr := Strings.New_String (Name & ": " & Value); begin Request.Curl_Headers := Curl_Slist_Append (Request.Curl_Headers, S); Interfaces.C.Strings.Free (S); end Process; begin if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Request.Iterate_Headers (Process'Access); end Set_Headers; procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("GET {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HTTPGET, 1); Check_Code (Result, "set http GET"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Get; procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("POST {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http POST"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Post; overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("PUT {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, PUT_TOKEN); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Put; overriding procedure Finalize (Request : in out Curl_Http_Request) is begin if Request.Data /= System.Null_Address then Curl_Easy_Cleanup (Request.Data); Request.Data := System.Null_Address; end if; if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Interfaces.C.Strings.Free (Request.URL); Interfaces.C.Strings.Free (Request.Content); end Finalize; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Curl_Http_Response) return String is begin return Ada.Strings.Unbounded.To_String (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Curl_Http_Response) return Natural is begin return Reply.Status; end Get_Status; end Util.Http.Clients.Curl;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Util.Http.Clients.Curl.Constants; package body Util.Http.Clients.Curl is use System; pragma Linker_Options ("-lcurl"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl"); function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access; PUT_TOKEN : Chars_Ptr := Strings.New_String ("PUT"); Manager : aliased Curl_Http_Manager; -- ------------------------------ -- Register the CURL Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. -- ------------------------------ procedure Check_Code (Code : in CURL_Code; Message : in String) is begin if Code /= CURLE_OK then declare Error : constant Chars_Ptr := Curl_Easy_Strerror (Code); Msg : constant String := Interfaces.C.Strings.Value (Error); begin Log.Error ("{0}: {1}", Message, Msg); raise Connection_Error with Msg; end; end if; end Check_Code; -- ------------------------------ -- Create a new HTTP request associated with the current request manager. -- ------------------------------ procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); Request : Curl_Http_Request_Access; Data : CURL; begin Data := Curl_Easy_Init; if Data = System.Null_Address then raise Storage_Error with "curl_easy_init cannot create the CURL instance"; end if; Request := new Curl_Http_Request; Request.Data := Data; Http.Delegate := Request.all'Access; end Create; function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is begin return Curl_Http_Request'Class (Http.Delegate.all)'Access; end Get_Request; -- ------------------------------ -- This function is called by CURL when a response line was read. -- ------------------------------ function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T is Total : constant Size_T := Size * Nmemb; Line : constant String := Interfaces.C.Strings.Value (Data, Total); begin Log.Info ("RCV: {0}", Line); if Response.Parsing_Body then Ada.Strings.Unbounded.Append (Response.Content, Line); elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then Response.Parsing_Body := True; else declare Pos : constant Natural := Util.Strings.Index (Line, ':'); Start : Natural; Last : Natural; begin if Pos > 0 then Start := Pos + 1; while Start <= Line'Last and Line (Start) = ' ' loop Start := Start + 1; end loop; Last := Line'Last; while Last >= Start and (Line (Last) = ASCII.CR or Line (Last) = ASCII.LF) loop Last := Last - 1; end loop; Response.Add_Header (Name => Line (Line'First .. Pos - 1), Value => Line (Start .. Last)); end if; end; end if; return Total; end Read_Response; -- ------------------------------ -- Prepare to setup the headers in the request. -- ------------------------------ procedure Set_Headers (Request : in out Curl_Http_Request) is procedure Process (Name, Value : in String) is S : Chars_Ptr := Strings.New_String (Name & ": " & Value); begin Request.Curl_Headers := Curl_Slist_Append (Request.Curl_Headers, S); Interfaces.C.Strings.Free (S); end Process; begin if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Request.Iterate_Headers (Process'Access); end Set_Headers; procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("GET {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HTTPGET, 1); Check_Code (Result, "set http GET"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Get; procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("POST {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http POST"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Post; overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("PUT {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Req.Set_Headers; Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, PUT_TOKEN); Check_Code (Result, "set http PUT"); Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers); Check_Code (Result, "set http GET headers"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Put; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in Curl_Http_Manager; Http : in Client'Class; Timeout : in Duration) is pragma Unreferenced (Manager); Req : constant Curl_Http_Request_Access := Get_Request (Http); Time : constant Interfaces.C.long := Interfaces.C.long (Timeout); Result : CURL_Code; begin Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_TIMEOUT, Time); Check_Code (Result, "set timeout"); end Set_Timeout; overriding procedure Finalize (Request : in out Curl_Http_Request) is begin if Request.Data /= System.Null_Address then Curl_Easy_Cleanup (Request.Data); Request.Data := System.Null_Address; end if; if Request.Curl_Headers /= null then Curl_Slist_Free_All (Request.Curl_Headers); Request.Curl_Headers := null; end if; Interfaces.C.Strings.Free (Request.URL); Interfaces.C.Strings.Free (Request.Content); end Finalize; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Curl_Http_Response) return String is begin return Ada.Strings.Unbounded.To_String (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Curl_Http_Response) return Natural is begin return Reply.Status; end Get_Status; end Util.Http.Clients.Curl;
Implement the Set_Timeout procedure
Implement the Set_Timeout procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2914446476b831a462bbd7c85ebf3a479e0e6786
src/asf-converters-numbers.ads
src/asf-converters-numbers.ads
----------------------------------------------------------------------- -- asf-converters -- ASF Converters -- 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 EL.Objects; -- with ASF.Components; -- with ASF.Contexts.Faces; -- The <b>ASF.Converters</b> defines an interface used by the conversion model -- to translate an object into a string when formatting the response and translate -- a string into an object during the apply request or validation phases (JSF postback). -- -- See JSR 314 - JavaServer Faces Specification 3.3.2 Converter -- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method) package ASF.Converters.Numbers is Invalid_Conversion : exception; -- ------------------------------ -- Converter -- ------------------------------ -- The <b>Object_Converter</b> is a must implement two functions to convert a string into -- an object and the opposite. The converter instance must be registered in -- the component factory (See <b>ASF.Factory.Component_Factory</b>). -- Unlike the Java implementation, the instance will be shared by multiple -- views and requests. type Object_Converter is abstract new Converter with null record; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- overriding -- function To_String (Convert : in Object_Converter; -- Context : in ASF.Contexts.Faces.Faces_Context'Class; -- Component : in ASF.Components.UIComponent'Class; -- Value : in EL.Objects.Object) return String; -- Convert the string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- overriding -- function To_Object (Convert : in Object_Converter; -- Context : in ASF.Contexts.Faces.Faces_Context'Class; -- Component : in ASF.Components.UIComponent'Class; -- Value : in String) return EL.Objects.Object; end ASF.Converters.Numbers;
----------------------------------------------------------------------- -- asf-converters-numbers -- Floating point number converters -- Copyright (C) 2010, 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 EL.Objects; with ASF.Components; with ASF.Contexts.Faces; with ASF.Locales; private with Util.Locales; private with Ada.Text_IO.Editing; -- The `ASF.Converters.Numbers` provides a floating point number converter. -- It can be used to print floating point numbers in various formats. package ASF.Converters.Numbers is type Number_Converter is new Converter with private; type Number_Converter_Access is access all Number_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. overriding function To_String (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) return String; -- Convert the string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. overriding function To_Object (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return EL.Objects.Object; -- Set the picture that must be used for the conversion. procedure Set_Picture (Converter : in out Number_Converter; Picture : in String); -- Get the currency to be used from the resource bundle in the user's current locale. function Get_Currency (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return String; -- Get the separator to be used from the resource bundle in the user's current locale. function Get_Separator (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; -- Get the radix mark to be used from the resource bundle in the user's current locale. function Get_Radix_Mark (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; -- Get the fill character to be used from the resource bundle in the user's current locale. function Get_Fill (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; private type Number_Converter is new Converter with record Picture : Ada.Text_IO.Editing.Picture; Locale : Util.Locales.Locale; Depend_On_Local : Boolean := False; end record; -- Get the locale that must be used to format the number. function Get_Locale (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; end ASF.Converters.Numbers;
Declare Number_Converter type with operations to convert a floating point number
Declare Number_Converter type with operations to convert a floating point number
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c1f353f38bfe6290ed15e5065c8ddbfb058062ab
awa/plugins/awa-changelogs/src/awa-changelogs-modules.adb
awa/plugins/awa-changelogs/src/awa-changelogs-modules.adb
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules.Get; with Util.Log.Loggers; package body AWA.Changelogs.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Changelogs.Module"); -- ------------------------------ -- Initialize the changelogs module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the changelogs module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the changelogs module. -- ------------------------------ function Get_Changelog_Module return Changelog_Module_Access is function Get is new AWA.Modules.Get (Changelog_Module, Changelog_Module_Access, NAME); begin return Get; end Get_Changelog_Module; end AWA.Changelogs.Modules;
----------------------------------------------------------------------- -- awa-changelogs-modules -- Module changelogs -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Changelogs.Models; with ADO.Sessions; with ADO.Sessions.Entities; package body AWA.Changelogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Changelogs.Module"); -- ------------------------------ -- Initialize the changelogs module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Changelog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the changelogs module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the changelogs module. -- ------------------------------ function Get_Changelog_Module return Changelog_Module_Access is function Get is new AWA.Modules.Get (Changelog_Module, Changelog_Module_Access, NAME); begin return Get; end Get_Changelog_Module; -- ------------------------------ -- Add the log message and associate it with the database entity identified by -- the given id and the entity type. The log message is associated with the current user. -- ------------------------------ procedure Add_Log (Model : in Changelog_Module; Id : in ADO.Identifier; Entity_Type : in String; Message : in String) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; History : AWA.Changelogs.Models.Changelog_Ref; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); History.Set_For_Entity_Id (Id); History.Set_User (User); History.Set_Date (Ada.Calendar.Clock); History.Set_Entity_Type (Kind); History.Set_Text (Message); History.Save (DB); DB.Commit; end Add_Log; end AWA.Changelogs.Modules;
Implement the Add_Log operation
Implement the Add_Log operation
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
a6d6e80ff15729027cbbb5f031ed4a40f584fcc8
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and 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; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and 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; Into : in out MAT.Memory.Allocation_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- 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); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Add the filter parameter to the Find operation
Add the filter parameter to the Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat