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
ba1c247bf07efa7ee99348f174c780e787110dcf
src/base/files/util-files.ads
src/base/files/util-files.ads
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); -- Delete the file including missing symbolic link -- or socket files (which GNAT fails to delete, -- see gcc/63222 and gcc/56055). The function returns 0 -- or the system error code. The procedure raises the Use_Error -- exception if the file cannot be deleted. function Delete_File (Path : in String) return Integer; procedure Delete_File (Path : in String); -- Delete the directory tree recursively. If the directory tree contains -- sockets, special files and dangling symbolic links, they are removed -- correctly. This is a workarround for GNAT bug gcc/63222 and gcc/56055. procedure Delete_Tree (Path : in String); end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); -- Delete the file including missing symbolic link -- or socket files (which GNAT fails to delete, -- see gcc/63222 and gcc/56055). The function returns 0 -- or the system error code. The procedure raises the Use_Error -- exception if the file cannot be deleted. function Delete_File (Path : in String) return Integer; procedure Delete_File (Path : in String); -- Delete the directory tree recursively. If the directory tree contains -- sockets, special files and dangling symbolic links, they are removed -- correctly. This is a workarround for GNAT bug gcc/63222 and gcc/56055. procedure Delete_Tree (Path : in String); -- Find the canonicalized absolute path of the given file. function Realpath (Path : in String) return String; end Util.Files;
Declare the Realpath function to give access to realpath (3) or GetFullPathNameW()
Declare the Realpath function to give access to realpath (3) or GetFullPathNameW()
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
06915f5d3043ecf0e2a1bdade3b11aab79baaaef
matp/src/mat-consoles.adb
matp/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; 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.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Formats.Size (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; -- ------------------------------ -- Get the field count that was setup through the Print_Title calls. -- ------------------------------ function Get_Field_Count (Console : in Console_Type) return Natural is begin return Console.Field_Count; end Get_Field_Count; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; 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.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Formats.Size (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; -- ------------------------------ -- Get the field count that was setup through the Print_Title calls. -- ------------------------------ function Get_Field_Count (Console : in Console_Type) return Natural is begin return Console.Field_Count; end Get_Field_Count; -- ------------------------------ -- Reset the field count. -- ------------------------------ procedure Clear_Fields (Console : in out Console_Type) is begin Console.Field_Count := 0; end Clear_Fields; end MAT.Consoles;
Implement the Clear_Fields procedure
Implement the Clear_Fields procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
437bddfbfde37090936e2316a577321414f795ec
src/natools-smaz_implementations-base_64.adb
src/natools-smaz_implementations-base_64.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, 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. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then Verbatim_Length := 64 - Natural (Code); Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (Natural (Code) - 61) * (Natural (Tools.Single_Byte_Padding'Last) + 1); Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 1) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 0 then declare Largest_Run : constant Positive := 64 * 3; Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 2; end; elsif Input_Length mod 3 = 1 then declare Largest_Final_Run : constant Positive := 15 * 3 + 1; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 2 then declare Largest_Final_Run : constant Positive := ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; else raise Program_Error with "Condition unreachable"; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Length, Last : Positive; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); Last := Index + Length - 1; Output (Offset) := Tools.Image (63 - Tools.Base_64_Digit (Length - 1)); Offset := Offset + 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
------------------------------------------------------------------------------ -- Copyright (c) 2016, 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. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_64 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; use type Tools.Base_64_Digit; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Verbatim_Length : out Natural; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Ignored : String (1 .. 2); Offset_Backup : Ada.Streams.Stream_Element_Offset; begin Tools.Next_Digit (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif Variable_Length_Verbatim then Verbatim_Length := 64 - Natural (Code); Code := 0; elsif Code = 63 then Tools.Next_Digit (Input, Offset, Code); Verbatim_Length := Natural (Code) * 3 + 3; Code := 0; elsif Code = 62 then Offset_Backup := Offset; Tools.Decode_Single (Input, Offset, Ignored (1), Code); Verbatim_Length := Natural (Code) * 3 + 1; Offset := Offset_Backup; Code := 0; else Offset_Backup := Offset; Verbatim_Length := (61 - Natural (Code)) * 4; Tools.Decode_Double (Input, Offset, Ignored, Code); Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2; Offset := Offset_Backup; Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is Ignored : Tools.Base_64_Digit; Output_Index : Natural := Output'First - 1; begin if Output'Length mod 3 = 1 then Tools.Decode_Single (Input, Offset, Output (Output_Index + 1), Ignored); Output_Index := Output_Index + 1; elsif Output'Length mod 3 = 2 then Tools.Decode_Double (Input, Offset, Output (Output_Index + 1 .. Output_Index + 2), Ignored); Output_Index := Output_Index + 2; end if; if Output_Index < Output'Last then Tools.Decode (Input, Offset, Output (Output_Index + 1 .. Output'Last)); end if; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 1) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 0 then declare Largest_Run : constant Positive := 64 * 3; Run_Count : constant Positive := (Input_Length + Largest_Run - 1) / Largest_Run; Last_Run_Size : constant Positive := Input_Length - (Run_Count - 1) * Largest_Run; begin return Ada.Streams.Stream_Element_Count (Run_Count - 1) * (Tools.Image_Length (Largest_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 2; end; elsif Input_Length mod 3 = 1 then declare Largest_Final_Run : constant Positive := 15 * 3 + 1; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; elsif Input_Length mod 3 = 2 then declare Largest_Final_Run : constant Positive := ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2; Largest_Prefix_Run : constant Positive := 64 * 3; Prefix_Run_Count : constant Natural := (Input_Length + Largest_Prefix_Run - Largest_Final_Run) / Largest_Prefix_Run; Last_Run_Size : constant Positive := Input_Length - Prefix_Run_Count * Largest_Prefix_Run; begin return Ada.Streams.Stream_Element_Count (Prefix_Run_Count) * (Tools.Image_Length (Largest_Prefix_Run) + 2) + Tools.Image_Length (Last_Run_Size) + 1; end; else raise Program_Error with "Condition unreachable"; end if; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is begin Output (Offset) := Tools.Image (Code); Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit; Variable_Length_Verbatim : in Boolean) is Index : Positive := Input'First; begin if Variable_Length_Verbatim then declare Largest_Run : constant Positive := 63 - Natural (Last_Code); Length, Last : Positive; begin while Index in Input'Range loop Length := Positive'Min (Largest_Run, Input'Last + 1 - Index); Last := Index + Length - 1; Output (Offset) := Tools.Image (63 - Tools.Base_64_Digit (Length - 1)); Offset := Offset + 1; Tools.Encode (Input (Index .. Last), Output, Offset); Index := Last + 1; end loop; end; else if Input'Length mod 3 = 1 then declare Extra_Blocks : constant Natural := Natural'Min (15, Input'Length / 3); begin Output (Offset) := Tools.Image (62); Offset := Offset + 1; Tools.Encode_Single (Input (Index), Tools.Single_Byte_Padding (Extra_Blocks), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; elsif Input'Length mod 3 = 2 then declare Extra_Blocks : constant Natural := Natural'Min (Input'Length / 3, (62 - Natural (Last_Code)) * 4 - 1); begin Output (Offset) := Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4)); Offset := Offset + 1; Tools.Encode_Double (Input (Index .. Index + 1), Tools.Double_Byte_Padding (Extra_Blocks mod 4), Output, Offset); Index := Index + 1; if Extra_Blocks > 0 then Tools.Encode (Input (Index .. Index + Extra_Blocks * 3 - 1), Output, Offset); Index := Index + Extra_Blocks * 3; end if; end; end if; pragma Assert ((Input'Last + 1 - Index) mod 3 = 0); while Index <= Input'Last loop declare Block_Count : constant Natural := Natural'Min (64, (Input'Last + 1 - Index) / 3); begin Output (Offset) := Tools.Image (63); Output (Offset + 1) := Tools.Image (Tools.Base_64_Digit (Block_Count - 1)); Offset := Offset + 2; Tools.Encode (Input (Index .. Index + Block_Count * 3 - 1), Output, Offset); Index := Index + Block_Count * 3; end; end loop; end if; end Write_Verbatim; end Natools.Smaz_Implementations.Base_64;
fix reading of 3n+2 verbatim length
smaz_implementations-base_64: fix reading of 3n+2 verbatim length A sign error caused a direct constraint error, and using the wrong type caused overlong reads (now 4 is hardcoded just like it is in encoding code).
Ada
isc
faelys/natools
90fcf3ad1e012985306146ff19a26885405b5e20
src/orka/implementation/orka-terminals.adb
src/orka/implementation/orka-terminals.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Ada.Text_IO; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : constant Duration := Orka.OS.Monotonic_Clock; Day_In_Seconds : constant := 24.0 * 60.0 * 60.0; function Time_Image return String is Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Day_In_Seconds loop Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds; Days_Since_Zero := Days_Since_Zero + 1; end loop; declare Seconds_Rounded : constant Natural := Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5)); Hour : constant Natural := Seconds_Rounded / 3600; Minute : constant Natural := (Seconds_Rounded mod 3600) / 60; Second : constant Natural := Seconds_Rounded mod 60; Sub_Second : constant Duration := Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second); -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration); type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); Last_Suffix : constant String_Access := Suffices (Suffices'Last); function Image (Value : Duration) return String is Result : String := "-9999.999"; Number : Duration := Value; Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin Duration_IO.Put (Result, Item => Number, Aft => 3); exception when others => return Number'Image & " " & Suffix.all; end; return Result & " " & Suffix.all; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : constant Duration := Orka.OS.Monotonic_Clock; Day_In_Seconds : constant := 24.0 * 60.0 * 60.0; function Time_Image return String is Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Day_In_Seconds loop Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds; Days_Since_Zero := Days_Since_Zero + 1; end loop; declare Seconds_Rounded : constant Natural := Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5)); Hour : constant Natural := Seconds_Rounded / 3600; Minute : constant Natural := (Seconds_Rounded mod 3600) / 60; Second : constant Natural := Seconds_Rounded mod 60; Sub_Second : constant Duration := Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second); -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; function Format (Value : Duration; Fore, Aft : Positive) return String is package SF renames Ada.Strings.Fixed; Aft_Shift : constant Positive := 10 ** Aft; New_Value : constant Duration := Duration (Natural (Value * Aft_Shift)) / Aft_Shift; S1 : constant String := SF.Trim (New_Value'Image, Ada.Strings.Both); Index_Decimal : constant Natural := SF.Index (S1, "."); -- Following code assumes that Aft >= 1 (If Aft = 0 then Aft must -- be decremented to remove the decimal point) S2 : constant String := S1 (S1'First .. Natural'Min (S1'Last, Index_Decimal + Aft)); S3 : constant String := SF.Tail (S2, Natural'Max (S2'Length, Fore + 1 + Aft), ' '); begin return S3; end Format; type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); Last_Suffix : constant String_Access := Suffices (Suffices'Last); function Image (Value : Duration) return String is Number : Duration := Value; Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin return Format (Number, Fore => 5, Aft => 3) & " " & Suffix.all; exception when others => return Number'Image & " " & Suffix.all; end; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
Remove usage of Ada.Text_IO.Fixed_IO in package Orka.Terminals
orka: Remove usage of Ada.Text_IO.Fixed_IO in package Orka.Terminals Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
847c74150f3fbe0ec57a21e40433fbf9c425ea75
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015, 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 Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with EL.Contexts.TLS; with Servlet.Core; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Services.Contexts; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant Servlet.Core.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Servlet.Core.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with EL.Contexts.TLS; with Servlet.Core; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant Servlet.Core.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Servlet.Core.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
69d15274797ca433263d15e9a4136c6e5970967d
matp/src/mat-formats.adb
matp/src/mat-formats.adb
----------------------------------------------------------------------- -- 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 Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- 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 is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- 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 is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_REALLOC => if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; 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 Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- 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 is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- 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 is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc(" & Size (Item.Size) & ")"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ")"; else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ")"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Add a brief or normal format type for events to print short description of malloc/realloc events
Add a brief or normal format type for events to print short description of malloc/realloc events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
13946061f50b555a17aa16e9ed1988711515a061
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.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;
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- Copyright (C) 2011, 2012, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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; 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;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4a0fb3ea8b98e3f22aa1a6d40343a4adcfd9765e
src/security-controllers-roles.adb
src/security-controllers-roles.adb
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Mappers.Record_Mapper; package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then for I in Handler.Roles'Range loop -- if P.Has_Role (Handler.Roles (I)) then return True; -- end if; end loop; end if; return False; end Has_Permission; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Permissions.Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Manager; Config_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Controllers.Roles;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- 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. ----------------------------------------------------------------------- package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then for I in Handler.Roles'Range loop -- if P.Has_Role (Handler.Roles (I)) then return True; -- end if; end loop; end if; return False; end Has_Permission; end Security.Controllers.Roles;
Remove the XML configuration reader which is now in Security.Policy.Roles
Remove the XML configuration reader which is now in Security.Policy.Roles
Ada
apache-2.0
Letractively/ada-security
fbdf54a0daa09f29e1bc4cf05c7e4b71a66c7ee1
ARM/STMicro/STM32/examples/balls/src/demo.adb
ARM/STMicro/STM32/examples/balls/src/demo.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- The file declares the main procedure for the demonstration. The LEDs -- will blink "in a circle" on the board. The blue user button generates -- an interrupt that changes the direction. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); -- The "last chance handler" is the user-defined routine that is called when -- an exception is propagated. We need it in the executable, therefore it -- must be somewhere in the closure of the context clauses. with System; with Interfaces; use Interfaces; with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.RNG.Interrupts; use STM32.RNG.Interrupts; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Demo is use STM32; pragma Priority (System.Priority'First); type HSV_Color is record Hue : Byte; Sat : Byte; Val : Byte; end record; function To_RGB (Col : HSV_Color) return DMA2D_Color; -- Translates a Hue/Saturation/Value color into RGB type Coordinate is (X, Y); type Vector is array (Coordinate) of Float; function "+" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) + V2 (X), Y => V1 (Y) + V2 (Y)); end "+"; function "-" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) - V2 (X), Y => V1 (Y) - V2 (Y)); end "-"; function "*" (V1, V2 : Vector) return Float is begin return V1 (X) * V2 (X) + V1 (Y) * V2 (Y); end "*"; function "*" (V : Vector; Val : Float) return Vector is begin return (V (X) * Val, V (Y) * Val); end "*"; function "/" (V : Vector; Val : Float) return Vector is begin return (V (X) / Val, V (Y) / Val); end "/"; type Moving_Object is record Center : Vector; Speed : Vector; R : Natural; Col : HSV_Color; N_Hue : Byte; end record; function I (F : Float) return Integer is (Integer (F)); function Collides (M1, M2 : Moving_Object) return Boolean; procedure Handle_Collision (M1, M2 : in out Moving_Object); Objects : array (1 .. 15) of Moving_Object; -- LCD_Config : LCD_Configuration; FG_Buffer : DMA2D_Buffer; ------------ -- To_RGB -- ------------ function To_RGB (Col : HSV_Color) return DMA2D_Color is V, S, H : Word; Region, FPart, p, q, t : Word; Ret : DMA2D_Color; begin Ret.Alpha := 255; if Col.Sat = 0 then Ret.Red := Col.Val; Ret.Green := Col.Val; Ret.Blue := Col.Val; return Ret; end if; V := Word (Col.Val); S := Word (Col.Sat); H := Word (Col.Hue); -- Hue in the range 0 .. 5 Region := H / 43; -- Division reminder, multiplied by 6 to make it in range 0 .. 255 FPart := (H - (Region * 43)) * 6; P := Shift_Right (V * (255 - S), 8); Q := Shift_Right (V * (255 - Shift_Right (S * FPart, 8)), 8); T := Shift_Right (V * (255 - Shift_Right (S * (255 - FPart), 8)), 8); case Region is when 0 => Ret.Red := Byte (V); Ret.Green := Byte (T); Ret.Blue := Byte (P); when 1 => Ret.Red := Byte (Q); Ret.Green := Byte (V); Ret.Blue := Byte (P); when 2 => Ret.Red := Byte (P); Ret.Green := Byte (V); Ret.Blue := Byte (T); when 3 => Ret.Red := Byte (P); Ret.Green := Byte (Q); Ret.Blue := Byte (V); when 4 => Ret.Red := Byte (T); Ret.Green := Byte (P); Ret.Blue := Byte (V); when others => Ret.Red := Byte (V); Ret.Green := Byte (P); Ret.Blue := Byte (Q); end case; return Ret; end To_RGB; ------------- -- Colides -- ------------- function Collides (M1, M2 : Moving_Object) return Boolean is Dist_Min_Square : constant Integer := (M1.R + M2.R) ** 2; M1_M2 : constant Vector := M2.Center - M1.Center; Dist_Square : constant Integer := (I (M1_M2 (X)) ** 2 + I (M1_M2 (Y)) ** 2); begin return Dist_Square < Dist_Min_Square; end Collides; ---------------------- -- Handle_Colisiton -- ---------------------- procedure Handle_Collision (M1, M2 : in out Moving_Object) is -- Dist: distance vector between the two objects Dist : Vector; -- Projx: Projection of the speed of Mx on Dist Tmp : Float; Proj1 : Vector; Proj2 : Vector; Tan_Sp1 : Vector; Tan_Sp2 : Vector; Sp1 : Vector; Sp2 : Vector; -- Simplified mass: equal to R Mass1 : constant Float := Float (M1.R); Mass2 : constant Float := Float (M2.R); dT : Float := 0.0; Old1, Old2 : Vector; begin -- Move back before collision -- If we don't, then the balls might still be touching themselves -- after we execute this procedure, so collision is called a second -- time afterwards. Old1 := M1.Center; Old2 := M2.Center; loop dT := dT + 0.2; M1.Center := Old1 - M1.Speed * dT; M2.Center := Old2 - M2.Speed * dT; exit when not Collides (M1, M2); end loop; Dist := (M2.Center - M1.Center); -- Calculate the projection vector of the speeds on Dist Tmp := (M1.Speed * Dist) / (Dist * Dist); Proj1 := Dist * Tmp; Tmp := (M2.Speed * Dist) / (Dist * Dist); Proj2 := Dist * Tmp; -- Now retrieve the speed that is tangantial to dist Tan_Sp1 := M1.Speed - Proj1; Tan_Sp2 := M2.Speed - Proj2; -- Transfer the projected speed from one object to the other Sp1 := (Proj1 * (Mass1 - Mass2) + Proj2 * 2.0 * Mass2) / (Mass1 + Mass2); Sp2 := (Proj2 * (Mass2 - Mass1) + Proj1 * 2.0 * Mass1) / (Mass1 + Mass2); -- Calculate the final speed of the objects: -- initial tangantial speed + calculated projected speed M1.Speed := Sp1 + Tan_Sp1; M2.Speed := Sp2 + Tan_Sp2; -- Now replay from the time of the impact with the new speed M1.Center := M1.Center + M1.Speed * dT; M2.Center := M2.Center + M2.Speed * dT; M1.N_Hue := M1.N_Hue + 32; M2.N_Hue := M2.N_Hue + 32; end Handle_Collision; ---------------- -- Init_Balls -- ---------------- procedure Init_Balls is Size : constant Integer := Natural'Min (Pixel_Width, Pixel_Height); R_Min : constant Natural := Size / 24; R_Var : constant Word := Word (R_Min) * 4 / 5; SP_Max : constant Integer := Size / 7; begin for J in Objects'Range loop loop declare O : Moving_Object renames Objects (J); R : constant Integer := Integer (RNG.Interrupts.Random mod R_Var) + R_Min; Col : constant Byte := Byte (RNG.Interrupts.Random mod 255); X_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Width - 2 * R)) + Word (R); Y_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Height - 2 * R)) + Word (R); Sp_X : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Sp_Y : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Redo : Boolean := False; begin O := (Center => (Float (Natural (X_Raw) + R), Float (Natural (Y_Raw) + R)), Speed => (Float (Sp_X) / 10.0, Float (Sp_Y) / 10.0), R => R, Col => (Hue => Col, Sat => 255, Val => 255), N_Hue => Col); for K in Objects'First .. J - 1 loop if Collides (O, Objects (K)) then Redo := True; exit; end if; end loop; exit when not Redo; end; end loop; end loop; end Init_Balls; begin STM32.LCD.Initialize (Pixel_Fmt_ARGB1555); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Double_Buffer, Layer_Foreground => Layer_Inactive); STM32.RNG.Interrupts.Initialize_RNG; -- STM32.Button.Initialize; -- STM32.LCD.Set_Layer_Alpha (BG, 255); Init_Balls; loop FG_Buffer := Double_Buffer.Get_Hidden_Buffer (Background); STM32.DMA2D.DMA2D_Fill (FG_Buffer, Black); for M of Objects loop if M.N_Hue /= M.Col.Hue then M.Col.Hue := M.Col.Hue + 1; end if; end loop; -- if STM32.Button.Has_Been_Pressed then -- -- dY := - dY; -- Init_Balls; -- end if; for O of Objects loop O.Center := O.Center + O.Speed; if (O.Speed (X) < 0.0 and then I (O.Center (X)) <= O.R) or else (O.Speed (X) > 0.0 and then I (O.Center (X)) + O.R >= Pixel_Width - 1) then O.Speed (X) := -O.Speed (X); O.Center (X) := O.Center (X) + O.Speed (X); end if; if (O.Speed (Y) < 0.0 and then I (O.Center (Y)) <= O.R) or else (O.Speed (Y) > 0.0 and then I (O.Center (Y)) + O.R >= Pixel_Height - 1) then O.Speed (Y) := -O.Speed (Y); O.Center (Y) := O.Center (Y) + O.Speed (Y); end if; end loop; for J in Objects'First .. Objects'Last - 1 loop for K in J + 1 .. Objects'Last loop if Collides (Objects (J), Objects (K)) then Handle_Collision (Objects (J), Objects (K)); end if; end loop; end loop; for O of Objects loop Fill_Circle (FG_Buffer, (X => I (O.Center (X)), Y => I (O.Center (Y))), O.R, To_RGB (O.Col)); end loop; Swap_Buffers (Vsync => True); end loop; end Demo;
------------------------------------------------------------------------------ -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- The file declares the main procedure for the demonstration. The LEDs -- will blink "in a circle" on the board. The blue user button generates -- an interrupt that changes the direction. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); -- The "last chance handler" is the user-defined routine that is called when -- an exception is propagated. We need it in the executable, therefore it -- must be somewhere in the closure of the context clauses. with System; with Interfaces; use Interfaces; with STM32.Button; use STM32.Button; with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.RNG.Interrupts; use STM32.RNG.Interrupts; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Demo is use STM32; pragma Priority (System.Priority'First); type HSV_Color is record Hue : Byte; Sat : Byte; Val : Byte; end record; function To_RGB (Col : HSV_Color) return DMA2D_Color; -- Translates a Hue/Saturation/Value color into RGB type Coordinate is (X, Y); type Vector is array (Coordinate) of Float; function "+" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) + V2 (X), Y => V1 (Y) + V2 (Y)); end "+"; function "-" (V1, V2 : Vector) return Vector is begin return (X => V1 (X) - V2 (X), Y => V1 (Y) - V2 (Y)); end "-"; function "*" (V1, V2 : Vector) return Float is begin return V1 (X) * V2 (X) + V1 (Y) * V2 (Y); end "*"; function "*" (V : Vector; Val : Float) return Vector is begin return (V (X) * Val, V (Y) * Val); end "*"; function "/" (V : Vector; Val : Float) return Vector is begin return (V (X) / Val, V (Y) / Val); end "/"; type Moving_Object is record Center : Vector; Speed : Vector; R : Natural; Col : HSV_Color; N_Hue : Byte; end record; function I (F : Float) return Integer is (Integer (F)); function Collides (M1, M2 : Moving_Object) return Boolean; procedure Handle_Collision (M1, M2 : in out Moving_Object); Objects : array (1 .. 15) of Moving_Object; FG_Buffer : DMA2D_Buffer; White_Background : Boolean := False; ------------ -- To_RGB -- ------------ function To_RGB (Col : HSV_Color) return DMA2D_Color is V, S, H : Word; Region, FPart, p, q, t : Word; Ret : DMA2D_Color; begin Ret.Alpha := 255; if Col.Sat = 0 then Ret.Red := Col.Val; Ret.Green := Col.Val; Ret.Blue := Col.Val; return Ret; end if; V := Word (Col.Val); S := Word (Col.Sat); H := Word (Col.Hue); -- Hue in the range 0 .. 5 Region := H / 43; -- Division reminder, multiplied by 6 to make it in range 0 .. 255 FPart := (H - (Region * 43)) * 6; P := Shift_Right (V * (255 - S), 8); Q := Shift_Right (V * (255 - Shift_Right (S * FPart, 8)), 8); T := Shift_Right (V * (255 - Shift_Right (S * (255 - FPart), 8)), 8); case Region is when 0 => Ret.Red := Byte (V); Ret.Green := Byte (T); Ret.Blue := Byte (P); when 1 => Ret.Red := Byte (Q); Ret.Green := Byte (V); Ret.Blue := Byte (P); when 2 => Ret.Red := Byte (P); Ret.Green := Byte (V); Ret.Blue := Byte (T); when 3 => Ret.Red := Byte (P); Ret.Green := Byte (Q); Ret.Blue := Byte (V); when 4 => Ret.Red := Byte (T); Ret.Green := Byte (P); Ret.Blue := Byte (V); when others => Ret.Red := Byte (V); Ret.Green := Byte (P); Ret.Blue := Byte (Q); end case; return Ret; end To_RGB; ------------- -- Colides -- ------------- function Collides (M1, M2 : Moving_Object) return Boolean is Dist_Min_Square : constant Integer := (M1.R + M2.R) ** 2; M1_M2 : constant Vector := M2.Center - M1.Center; Dist_Square : constant Integer := (I (M1_M2 (X)) ** 2 + I (M1_M2 (Y)) ** 2); begin return Dist_Square < Dist_Min_Square; end Collides; ---------------------- -- Handle_Colisiton -- ---------------------- procedure Handle_Collision (M1, M2 : in out Moving_Object) is -- Dist: distance vector between the two objects Dist : Vector; -- Projx: Projection of the speed of Mx on Dist Tmp : Float; Proj1 : Vector; Proj2 : Vector; Tan_Sp1 : Vector; Tan_Sp2 : Vector; Sp1 : Vector; Sp2 : Vector; -- Simplified mass: equal to R^2 Mass1 : constant Float := Float (M1.R ** 2); Mass2 : constant Float := Float (M2.R ** 2); dT : Float := 0.0; Old1, Old2 : Vector; begin -- Move back before collision -- If we don't, then the balls might still be touching themselves -- after we execute this procedure, so collision is called a second -- time afterwards. Old1 := M1.Center; Old2 := M2.Center; loop dT := dT + 0.2; M1.Center := Old1 - M1.Speed * dT; M2.Center := Old2 - M2.Speed * dT; exit when not Collides (M1, M2); end loop; Dist := (M2.Center - M1.Center); -- Calculate the projection vector of the speeds on Dist Tmp := (M1.Speed * Dist) / (Dist * Dist); Proj1 := Dist * Tmp; Tmp := (M2.Speed * Dist) / (Dist * Dist); Proj2 := Dist * Tmp; -- Now retrieve the speed that is tangantial to dist Tan_Sp1 := M1.Speed - Proj1; Tan_Sp2 := M2.Speed - Proj2; -- Transfer the projected speed from one object to the other Sp1 := (Proj1 * (Mass1 - Mass2) + Proj2 * 2.0 * Mass2) / (Mass1 + Mass2); Sp2 := (Proj2 * (Mass2 - Mass1) + Proj1 * 2.0 * Mass1) / (Mass1 + Mass2); -- Calculate the final speed of the objects: -- initial tangantial speed + calculated projected speed M1.Speed := Sp1 + Tan_Sp1; M2.Speed := Sp2 + Tan_Sp2; -- Now replay from the time of the impact with the new speed M1.Center := M1.Center + M1.Speed * dT; M2.Center := M2.Center + M2.Speed * dT; M1.N_Hue := M1.N_Hue + 32; M2.N_Hue := M2.N_Hue + 32; end Handle_Collision; ---------------- -- Init_Balls -- ---------------- procedure Init_Balls is Size : constant Integer := Natural'Min (Pixel_Width, Pixel_Height); R_Min : constant Natural := Size / 24; R_Var : constant Word := Word (R_Min) * 4 / 5; SP_Max : constant Integer := Size / 7; begin for J in Objects'Range loop loop declare O : Moving_Object renames Objects (J); R : constant Integer := Integer (RNG.Interrupts.Random mod R_Var) + R_Min; Col : constant Byte := Byte (RNG.Interrupts.Random mod 255); X_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Width - 2 * R)) + Word (R); Y_Raw : constant Word := (RNG.Interrupts.Random mod Word (Pixel_Height - 2 * R)) + Word (R); Sp_X : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Sp_Y : constant Integer := Integer (RNG.Interrupts.Random mod Word (SP_Max * 2 + 1)) - SP_Max; Redo : Boolean := False; begin O := (Center => (Float (Natural (X_Raw) + R), Float (Natural (Y_Raw) + R)), Speed => (Float (Sp_X) / 10.0, Float (Sp_Y) / 10.0), R => R, Col => (Hue => Col, Sat => 255, Val => 255), N_Hue => Col); for K in Objects'First .. J - 1 loop if Collides (O, Objects (K)) then Redo := True; exit; end if; end loop; exit when not Redo; end; end loop; end loop; end Init_Balls; begin STM32.LCD.Initialize (Pixel_Fmt_ARGB1555); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Double_Buffer, Layer_Foreground => Layer_Inactive); STM32.RNG.Interrupts.Initialize_RNG; STM32.Button.Initialize; Init_Balls; loop if STM32.Button.Has_Been_Pressed then White_Background := not White_Background; end if; FG_Buffer := Double_Buffer.Get_Hidden_Buffer (Background); STM32.DMA2D.DMA2D_Fill (FG_Buffer, (if White_Background then White else Black)); for M of Objects loop if M.N_Hue /= M.Col.Hue then M.Col.Hue := M.Col.Hue + 1; end if; end loop; for O of Objects loop O.Center := O.Center + O.Speed; if (O.Speed (X) < 0.0 and then I (O.Center (X)) <= O.R) or else (O.Speed (X) > 0.0 and then I (O.Center (X)) + O.R >= Pixel_Width - 1) then O.Speed (X) := -O.Speed (X); O.Center (X) := O.Center (X) + O.Speed (X); end if; if (O.Speed (Y) < 0.0 and then I (O.Center (Y)) <= O.R) or else (O.Speed (Y) > 0.0 and then I (O.Center (Y)) + O.R >= Pixel_Height - 1) then O.Speed (Y) := -O.Speed (Y); O.Center (Y) := O.Center (Y) + O.Speed (Y); end if; end loop; for J in Objects'First .. Objects'Last - 1 loop for K in J + 1 .. Objects'Last loop if Collides (Objects (J), Objects (K)) then Handle_Collision (Objects (J), Objects (K)); end if; end loop; end loop; for O of Objects loop Fill_Circle (FG_Buffer, (X => I (O.Center (X)), Y => I (O.Center (Y))), O.R, To_RGB (O.Col)); end loop; Swap_Buffers (Vsync => True); end loop; end Demo;
Improve the "Balls" example by switching the background color upon button.
Improve the "Balls" example by switching the background color upon button.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
92e9fb12967192e6b2cebd63fc3548dc7aa316cc
regtests/util-beans-objects-tests.adb
regtests/util-beans-objects-tests.adb
----------------------------------------------------------------------- -- util-beans-objects-tests -- Unit tests for objects -- 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; with Util.Beans.Objects.Maps; package body Util.Beans.Objects.Tests is package Caller is new Util.Test_Caller (Test, "Objects"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Is_Array", Test_Is_Array'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Get_Count", Test_Get_Count'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Get_Value", Test_Get_Value'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Set_Value", Test_Set_Value'Access); end Add_Tests; -- ------------------------------ -- Test the creation, initialization and retrieval of objects holding arrays. -- ------------------------------ procedure Test_Is_Array (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); T.Assert (not Is_Null (Value), "Array object must not be null"); T.Assert (not Is_Empty (Value), "Array object must not be empty"); T.Assert (Is_Array (Value), "Array object must be an array"); for I in List'Range loop T.Assert (not Is_Array (List (I)), "Is_Array returned true for non array object"); end loop; T.Assert (not Is_Array (Null_Object), "The Null_Object is not an array"); end Test_Is_Array; -- ------------------------------ -- Test the Get_Count operation. -- ------------------------------ procedure Test_Get_Count (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); Util.Tests.Assert_Equals (T, List'Length, Get_Count (Value), "Get_Count is invalid"); Util.Tests.Assert_Equals (T, 0, Get_Count (Null_Object), "Get_Count is invalid"); end Test_Get_Count; -- ------------------------------ -- Test the Get_Value operation. -- ------------------------------ procedure Test_Get_Value (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; Item : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); for I in 1 .. Get_Count (Value) loop Item := Get_Value (Value, I); T.Assert (not Is_Null (Item), "Item at " & Positive'Image (I) & " is null"); end loop; end Test_Get_Value; -- ------------------------------ -- Test the Set_Value operation. -- ------------------------------ procedure Test_Set_Value (T : in out Test) is List : Object_Array (1 .. 10); Value : Object := Maps.Create; Item : Object; begin Set_Value (Value, "username", To_Object (String '("joe"))); Set_Value (Value, "age", To_Object (Integer (32))); Util.Tests.Assert_Equals (T, "joe", To_String (Get_Value (Value, "username"))); Util.Tests.Assert_Equals (T, 32, To_Integer (Get_Value (Value, "age"))); end Test_Set_Value; end Util.Beans.Objects.Tests;
----------------------------------------------------------------------- -- util-beans-objects-tests -- Unit tests for objects -- 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; with Util.Beans.Objects.Maps; package body Util.Beans.Objects.Tests is package Caller is new Util.Test_Caller (Test, "Objects"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Is_Array", Test_Is_Array'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Get_Count", Test_Get_Count'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Get_Value", Test_Get_Value'Access); Caller.Add_Test (Suite, "Test Util.Beans.Objects.Set_Value", Test_Set_Value'Access); end Add_Tests; -- ------------------------------ -- Test the creation, initialization and retrieval of objects holding arrays. -- ------------------------------ procedure Test_Is_Array (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); T.Assert (not Is_Null (Value), "Array object must not be null"); T.Assert (not Is_Empty (Value), "Array object must not be empty"); T.Assert (Is_Array (Value), "Array object must be an array"); for I in List'Range loop T.Assert (not Is_Array (List (I)), "Is_Array returned true for non array object"); end loop; T.Assert (not Is_Array (Null_Object), "The Null_Object is not an array"); end Test_Is_Array; -- ------------------------------ -- Test the Get_Count operation. -- ------------------------------ procedure Test_Get_Count (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); Util.Tests.Assert_Equals (T, List'Length, Get_Count (Value), "Get_Count is invalid"); Util.Tests.Assert_Equals (T, 0, Get_Count (Null_Object), "Get_Count is invalid"); end Test_Get_Count; -- ------------------------------ -- Test the Get_Value operation. -- ------------------------------ procedure Test_Get_Value (T : in out Test) is List : Object_Array (1 .. 10); Value : Object; Item : Object; begin for I in List'Range loop List (I) := To_Object (I); end loop; Value := To_Object (List); for I in 1 .. Get_Count (Value) loop Item := Get_Value (Value, I); T.Assert (not Is_Null (Item), "Item at " & Positive'Image (I) & " is null"); end loop; end Test_Get_Value; -- ------------------------------ -- Test the Set_Value operation. -- ------------------------------ procedure Test_Set_Value (T : in out Test) is Value : constant Object := Maps.Create; begin Set_Value (Value, "username", To_Object (String '("joe"))); Set_Value (Value, "age", To_Object (Integer (32))); Util.Tests.Assert_Equals (T, "joe", To_String (Get_Value (Value, "username"))); Util.Tests.Assert_Equals (T, 32, To_Integer (Get_Value (Value, "age"))); end Test_Set_Value; end Util.Beans.Objects.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
06cb991a2161bb3a7efcfaa779e1fd7b46165bc9
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
Add test to verify the Get_Size function on the column
Add test to verify the Get_Size function on the column
Ada
apache-2.0
stcarrez/ada-ado
f38cd44b91fd8c4138a95d411cbcda5cda2ed889
regtests/ado-audits-tests.adb
regtests/ado-audits-tests.adb
----------------------------------------------------------------------- -- ado-audits-tests -- Audit tests -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Ada.Text_IO; with Regtests.Audits.Model; with ADO.SQL; with ADO.Sessions.Entities; package body ADO.Audits.Tests is use type ADO.Objects.Object_Key_Type; package Caller is new Util.Test_Caller (Test, "ADO.Audits"); type Test_Audit_Manager is new Audit_Manager with null record; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array); Audit_Instance : aliased Test_Audit_Manager; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array) is pragma Unreferenced (Manager); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : Regtests.Audits.Model.Audit_Ref; begin if Object.Key_Type = ADO.Objects.KEY_INTEGER then Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); end if; Audit.Set_Entity_Type (Kind); Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); Audit.Set_New_Value (UBO.To_String (C.New_Value)); Audit.Set_Date (Now); Audit.Save (Session); end; end loop; end Save; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field", Test_Audit_Field'Access); end Add_Tests; procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Regtests.Set_Audit_Manager (Audit_Instance'Access); end Set_Up; -- ------------------------------ -- Test populating Audit_Fields -- ------------------------------ procedure Test_Audit_Field (T : in out Test) is type Identifier_Array is array (1 .. 10) of ADO.Identifier; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Email : Regtests.Audits.Model.Email_Ref; Prop : Regtests.Audits.Model.Property_Ref; List : Identifier_Array; begin for I in List'Range loop Email := Regtests.Audits.Model.Null_Email; Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com"); Email.Set_Status (ADO.Nullable_Integer '(23, False)); Email.Save (DB); List (I) := Email.Get_Id; end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com"); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com"); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Null_Integer); Email.Save (DB); end loop; DB.Commit; for I in 1 .. 10 loop Prop.Set_Value ((Value => I, Is_Null => False)); Prop.Set_Float_Value (3.0 * Float (I)); Prop.Save (DB); end loop; declare Query : ADO.SQL.Query; Audit_List : Regtests.Audits.Model.Audit_Vector; begin Query.Set_Filter ("entity_id = :entity_id"); for Id of List loop Query.Bind_Param ("entity_id", Id); Regtests.Audits.Model.List (Audit_List, DB, Query); for A of Audit_List loop Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " " & ADO.Identifier'Image (A.Get_Id) & " " & A.Get_Old_Value & " - " & A.Get_New_Value); Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id), "Invalid audit record: id is wrong"); end loop; Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length), "Invalid number of audit records"); end loop; end; end Test_Audit_Field; end ADO.Audits.Tests;
----------------------------------------------------------------------- -- ado-audits-tests -- Audit tests -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Ada.Text_IO; with Regtests.Audits.Model; with ADO.SQL; with ADO.Sessions.Entities; package body ADO.Audits.Tests is use type ADO.Objects.Object_Key_Type; package Caller is new Util.Test_Caller (Test, "ADO.Audits"); type Test_Audit_Manager is new Audit_Manager with null record; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array); Audit_Instance : aliased Test_Audit_Manager; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array) is pragma Unreferenced (Manager); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : Regtests.Audits.Model.Audit_Ref; begin if Object.Key_Type = ADO.Objects.KEY_INTEGER then Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); end if; Audit.Set_Entity_Type (Kind); Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); Audit.Set_New_Value (UBO.To_String (C.New_Value)); Audit.Set_Date (Now); Audit.Save (Session); end; end loop; end Save; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field", Test_Audit_Field'Access); end Add_Tests; procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Regtests.Set_Audit_Manager (Audit_Instance'Access); end Set_Up; -- ------------------------------ -- Test populating Audit_Fields -- ------------------------------ procedure Test_Audit_Field (T : in out Test) is type Identifier_Array is array (1 .. 10) of ADO.Identifier; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Email : Regtests.Audits.Model.Email_Ref; Prop : Regtests.Audits.Model.Property_Ref; List : Identifier_Array; begin for I in List'Range loop Email := Regtests.Audits.Model.Null_Email; Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com"); Email.Set_Status (ADO.Nullable_Integer '(23, False)); Email.Save (DB); List (I) := Email.Get_Id; end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com"); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com"); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Null_Integer); Email.Save (DB); end loop; DB.Commit; Prop.set_Id (Util.Tests.Get_Uuid); for I in 1 .. 10 loop Prop.Set_Value ((Value => I, Is_Null => False)); Prop.Set_Float_Value (3.0 * Float (I)); Prop.Save (DB); end loop; declare Query : ADO.SQL.Query; Audit_List : Regtests.Audits.Model.Audit_Vector; begin Query.Set_Filter ("entity_id = :entity_id"); for Id of List loop Query.Bind_Param ("entity_id", Id); Regtests.Audits.Model.List (Audit_List, DB, Query); for A of Audit_List loop Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " " & ADO.Identifier'Image (A.Get_Id) & " " & A.Get_Old_Value & " - " & A.Get_New_Value); Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id), "Invalid audit record: id is wrong"); end loop; Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length), "Invalid number of audit records"); end loop; end; end Test_Audit_Field; end ADO.Audits.Tests;
Fix running the test several times: avoid duplicate key when inserting a property for the test
Fix running the test several times: avoid duplicate key when inserting a property for the test
Ada
apache-2.0
stcarrez/ada-ado
c986dc79430d3f7e6da62ac80b874d1cb112fb85
src/security-contexts.adb
src/security-contexts.adb
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Security.Controllers; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Permissions.Controller_Access; use type Security.Permissions.Permission_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Permissions.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else Result := C.Has_Permission (Context); end if; end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. -- ------------------------------ procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- ------------------------------ function Get_Context (Context : in Security_Context; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- Returns True if a context information was registered under the name <b>Name</b>. -- ------------------------------ function Has_Context (Context : in Security_Context; Name : in String) return Boolean is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Permissions.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Security.Controllers; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Permissions.Controller_Access; use type Security.Permissions.Permission_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Permissions.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else Result := C.Has_Permission (Context); end if; end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. -- ------------------------------ procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- ------------------------------ function Get_Context (Context : in Security_Context; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- Returns True if a context information was registered under the name <b>Name</b>. -- ------------------------------ function Has_Context (Context : in Security_Context; Name : in String) return Boolean is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
Use the Principal from the Security package
Use the Principal from the Security package
Ada
apache-2.0
Letractively/ada-security
8a0ef57659744c336544eff54957b34ae8a52b1b
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); Free (Manager.Permissions (Index)); end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); Free (Manager.Permissions (Index)); end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Finish_Config; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Read the configuration file. Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; end Security.Policies;
Implement the new procedure Prepare_Config and Finish_Config Call them in Read_Policy
Implement the new procedure Prepare_Config and Finish_Config Call them in Read_Policy
Ada
apache-2.0
Letractively/ada-security
17bd76be32a9c31de8117f4478514ef13658b16b
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; -- 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; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_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;
----------------------------------------------------------------------- -- 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; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_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;
Add the <<Nullable>> and <<Not Null>> stereotypes
Add the <<Nullable>> and <<Not Null>> stereotypes
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
c8f2b1ab4f541f3a6fc9139fc60980f085fcfb4e
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- -- @include security-policies-roles.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Add some documentation
Add some documentation
Ada
apache-2.0
Letractively/ada-security
6ccd387f2b253d342aafc794780db604763e6b2a
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Threads command. -- Collect statistics about the threads and their allocation. -- ------------------------------ procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Threads : MAT.Memory.Memory_Info_Map; Iter : MAT.Memory.Memory_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10); Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15); Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15); Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15); Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15); Console.End_Title; MAT.Memory.Targets.Thread_Information (Memory => Target.Memory, Threads => Threads); Iter := Threads.First; while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter); Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter); begin Console.Start_Row; Console.Print_Field (MAT.Consoles.F_THREAD, Thread); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count); Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size); Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size); Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size); Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr); Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr); Console.End_Row; end; MAT.Memory.Memory_Info_Maps.Next (Iter); end loop; end Threads_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Target.Console.Error ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); Commands.Insert ("threads", Threads_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Threads command. -- Collect statistics about the threads and their allocation. -- ------------------------------ procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Threads : MAT.Memory.Memory_Info_Map; Iter : MAT.Memory.Memory_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_Thread, "Thread", 10); Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15); Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15); Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15); Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15); Console.End_Title; MAT.Memory.Targets.Thread_Information (Memory => Target.Memory, Threads => Threads); Iter := Threads.First; while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter); Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter); begin Console.Start_Row; Console.Print_Field (MAT.Consoles.F_THREAD, Integer (Thread)); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count); Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size); Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size); Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size); Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr); Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr); Console.End_Row; end; MAT.Memory.Memory_Info_Maps.Next (Iter); end loop; end Threads_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Target.Console.Error ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); Commands.Insert ("threads", Threads_Command'Access); end MAT.Commands;
Format the thread ID as an integer
Format the thread ID as an integer
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
88cd1598ad0f5b6097cead1c960f6742068d1e60
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; with ASF.Requests; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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 Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
c7100c32ca7fea81e06d93b8373b98b1ab1caecd
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; Element : in File_Type) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Element : in Directory_Type) 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; -- Create a new directory instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return Directory_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; type Default_Container is new File_Container with private; -- Add the file with the given name in the container. procedure Add_File (Into : in out Default_Container; Element : in File_Type); -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. function Create (Into : in Default_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. function Create (Into : in Default_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. function Find (From : in Default_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. function Find (From : in Default_Container; Name : in String) return Directory_Type; 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; type Default_Container is new Babel.Files.File_Container with record Current : Directory_Type; end record; 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; Element : in File_Type) is abstract; -- Add the directory with the given name in the container. procedure Add_Directory (Into : in out File_Container; Element : in Directory_Type) 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; -- Create a new directory instance with the given name in the container. function Create (Into : in File_Container; Name : in String) return Directory_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; type Default_Container is new File_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Default_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Default_Container; Name : in String) return Directory_Type; 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; type Default_Container is new Babel.Files.File_Container with record Current : Directory_Type; end record; NO_DIRECTORY : constant Directory_Type := null; NO_FILE : constant File_Type := null; end Babel.Files;
Mark the Default_Container operation as overriding
Mark the Default_Container operation as overriding
Ada
apache-2.0
stcarrez/babel
1be8f2886803caa9dcdb15697dd26f93fa98a0be
regtests/util-streams-buffered-tests.adb
regtests/util-streams-buffered-tests.adb
----------------------------------------------------------------------- -- streams.buffered.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Texts; package body Util.Streams.Buffered.Tests is use Util.Tests; use Util.Streams.Texts; package Caller is new Util.Test_Caller (Test, "Streams.Buffered"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)", Test_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)", Test_Write_Stream'Access); end Add_Tests; -- ------------------------------ -- Write on a buffered stream and read what was written. -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); Stream.Write ("abcd"); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "abcd", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Read_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 1000; Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2; begin Big_Stream.Initialize (Size => Natural (Max_Size)); Stream.Initialize (Output => Big_Stream'Access, Size => 13); for I in 1 .. Count loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element (J mod 255); end loop; Stream.Write (S); Stream.Flush; Size := Size + I; Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I)); end; end loop; end Test_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write_Stream (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 200; Max_Size : constant Stream_Element_Offset := 5728500; begin Big_Stream.Initialize (Size => Natural (Max_Size)); for Buf_Size in 1 .. 19 loop Stream.Initialize (Output => Big_Stream'Access, Size => Buf_Size); for I in 1 .. Count loop for Repeat in 1 .. 5 loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element'Val (J mod 255); end loop; for J in 1 .. Repeat loop Stream.Write (S); end loop; Stream.Flush; Size := Size + (I) * Stream_Element_Offset (Repeat); Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I) & " with buffer " & Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat)); end; end loop; end loop; end loop; Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size"); end Test_Write_Stream; end Util.Streams.Buffered.Tests;
----------------------------------------------------------------------- -- streams.buffered.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 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.Wide_Wide_Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Texts; with Util.Streams.Files; package body Util.Streams.Buffered.Tests is pragma Wide_Character_Encoding (UTF8); use Util.Tests; use Util.Streams.Texts; package Caller is new Util.Test_Caller (Test, "Streams.Buffered"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)", Test_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)", Test_Write_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Read (UTF-8)", Test_Read_UTF_8'Access); end Add_Tests; -- ------------------------------ -- Write on a buffered stream and read what was written. -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); Stream.Write ("abcd"); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "abcd", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Read_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 1000; Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2; begin Big_Stream.Initialize (Size => Natural (Max_Size)); Stream.Initialize (Output => Big_Stream'Access, Size => 13); for I in 1 .. Count loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element (J mod 255); end loop; Stream.Write (S); Stream.Flush; Size := Size + I; Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I)); end; end loop; end Test_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write_Stream (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 200; Max_Size : constant Stream_Element_Offset := 5728500; begin Big_Stream.Initialize (Size => Natural (Max_Size)); for Buf_Size in 1 .. 19 loop Stream.Initialize (Output => Big_Stream'Access, Size => Buf_Size); for I in 1 .. Count loop for Repeat in 1 .. 5 loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element'Val (J mod 255); end loop; for J in 1 .. Repeat loop Stream.Write (S); end loop; Stream.Flush; Size := Size + (I) * Stream_Element_Offset (Repeat); Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I) & " with buffer " & Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat)); end; end loop; end loop; end loop; Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size"); end Test_Write_Stream; -- ------------------------------ -- Test reading UTF-8 file. -- ------------------------------ procedure Test_Read_UTF_8 (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Stream : Util.Streams.Buffered.Input_Buffer_Stream; Path : constant String := Util.Tests.Get_Path ("regtests/files/utf-8.txt"); begin Stream.Initialize (Input => File'Access, Size => 1024); File.Open (Ada.Streams.Stream_IO.In_File, Path); declare S : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Expect : constant Wide_Wide_String := "àéúíòࠀ€ಜ࠴𝄞" & Wide_Wide_Character'Val (16#0A#); begin Stream.Read (S); declare Result : constant Wide_Wide_String := Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (S); begin if Expect /= Result then T.Fail ("Invalid UTF-8 string"); end if; end; end; end Test_Read_UTF_8; end Util.Streams.Buffered.Tests;
Implement Test_Read_UTF_8 to check reading UTF-8 sequences
Implement Test_Read_UTF_8 to check reading UTF-8 sequences
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4f8bd6f5b0c9633cfd2a36d1710d154f7ebfd5be
regtests/ado-parameters-tests.adb
regtests/ado-parameters-tests.adb
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; package body ADO.Parameters.Tests is use Util.Tests; type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; end ADO.Parameters.Tests;
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO.Caches.Discrete; with ADO.Caches; package body ADO.Parameters.Tests is use Util.Tests; package Int_Cache is new ADO.Caches.Discrete (Element_Type => Integer); type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (cache expander)", Test_Expand_With_Expander'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; -- ------------------------------ -- Test expand with cache expander. -- ------------------------------ procedure Test_Expand_With_Expander (T : in out Test) is procedure Check (Content : in String; Expect : in String); SQL : ADO.Parameters.List; D : aliased Dialect; C : aliased ADO.Caches.Cache_Manager; M : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; P : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; procedure Check (Content : in String; Expect : in String) is S : constant String := SQL.Expand (Content); begin Util.Tests.Assert_Equals (T, Expect, S, "Invalid expand for SQL '" & Content & "'"); end Check; begin C.Add_Cache ("test-group", M.all'Access); C.Add_Cache ("G2", P.all'Access); SQL.Expander := C'Unchecked_Access; M.Insert ("value-1", 123); M.Insert ("2", 2); M.Insert ("a name", 10); P.Insert ("1", 10); P.Insert ("a", 0); P.Insert ("c", 1); SQL.Set_Dialect (D'Unchecked_Access); Check ("$test-group[2]", "2"); Check ("$test-group[a name]", "10"); Check ("SELECT * FROM user WHERE id = $test-group[2]+$test-group[value-1]", "SELECT * FROM user WHERE id = 2+123"); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 0+123"); P.Insert ("a", 1, True); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 1+123"); end Test_Expand_With_Expander; end ADO.Parameters.Tests;
Implement the Test_Expand_With_Expander and register the new unit test
Implement the Test_Expand_With_Expander and register the new unit test
Ada
apache-2.0
stcarrez/ada-ado
d756b9f33119ef81cd8a97cc20f4b29f2452e6c0
src/base/files/util-files.ads
src/base/files/util-files.ads
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ":"); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in String := ";") return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); end Util.Files;
Update Find_File_Path to use a Character for the Separator
Update Find_File_Path to use a Character for the Separator
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0870e646395444bfc557654681eeb60d28a9b1fe
src/base/files/util-files.ads
src/base/files/util-files.ads
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); -- Delete the file including missing symbolic link -- or socket files (which GNAT fails to delete, -- see gcc/63222 and gcc/56055). procedure Delete_File (Path : in String); end Util.Files;
Declare the Delete_File procedure to workarround GNAT bug that cannot delete some files
Declare the Delete_File procedure to workarround GNAT bug that cannot delete some files
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6818a85e4d41cb6d11aa9bdd1ef06b15f5f03b44
src/gen-commands-generate.ads
src/gen-commands-generate.ads
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Generate is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Generate;
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Generate is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Generate;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
8e0f70880f0b2789e8aa90ce3bb02b037c1038b3
mat/src/mat-readers-streams.adb
mat/src/mat-readers-streams.adb
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 3; Reader.Stream.Read (Data (0 .. 2), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Stream.Read (Data (0 .. 1), Last); exit when Last /= 2; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); exit; end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Dispatch_Message (Msg); end loop; end Read_All; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 3; Reader.Stream.Read (Data (0 .. 2), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Stream.Read (Data (0 .. 1), Last); exit when Last /= 2; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); exit; end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Dispatch_Message (Msg); end loop; end Read_All; end MAT.Readers.Streams;
Implement the Read_Message procedure
Implement the Read_Message procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2cd692ab7a39b07d66f9b6be3337a2ea4b8b11f0
src/util-serialize-io-csv.ads
src/util-serialize-io-csv.ads
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; end record; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; end record; end Util.Serialize.IO.CSV;
Declare the Write_Cell, Write_Wide_Entity, Write_Wide_Attribute procedures for CSV stream generation
Declare the Write_Cell, Write_Wide_Entity, Write_Wide_Attribute procedures for CSV stream generation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b70c940150d5778bbc40eda93aaa8110ceccfeca
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; begin if P /= null then for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing) is Perm : Security.Controllers.URLs.URL_Controller_Access; begin Mapper.Add_Mapping ("policy-rules", Policy_Mapping'Access); Mapper.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Mapper, Policy'Unchecked_Access); if not Policy.Manager.Has_Controller (P_URL.Permission) then Perm := new Security.Controllers.URLs.URL_Controller; Perm.Manager := Policy'Unchecked_Access; Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end if; end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Ref.Element_Accessor := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.Map := Rules.Map; New_Ref.Value.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. if not Rule.Is_Null then declare P : constant Access_Rule_Refs.Element_Accessor := Rule.Value; begin for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end; end if; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Atomic_Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Atomic_Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing) is Perm : Security.Controllers.URLs.URL_Controller_Access; begin Mapper.Add_Mapping ("policy-rules", Policy_Mapping'Access); Mapper.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Mapper, Policy'Unchecked_Access); if not Policy.Manager.Has_Controller (P_URL.Permission) then Perm := new Security.Controllers.URLs.URL_Controller; Perm.Manager := Policy'Unchecked_Access; Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end if; end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
Update after changes in Util.Refs package
Update after changes in Util.Refs package
Ada
apache-2.0
stcarrez/ada-security
90d3eecf36fec3e85e2f0edc9c6d7a251e892d0a
src/util-concurrent-arrays.adb
src/util-concurrent-arrays.adb
----------------------------------------------------------------------- -- Util.Concurrent.Arrays -- Concurrent Arrays -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Arrays is procedure Free is new Ada.Unchecked_Deallocation (Object => Vector_Record, Name => Vector_Record_Access); -- ------------------------------ -- Returns True if the container is empty. -- ------------------------------ function Is_Empty (Container : in Ref) return Boolean is begin return Container.Target = null; end Is_Empty; -- ------------------------------ -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in Target.List'Range loop Process (Target.List (I)); end loop; end if; end Iterate; -- ------------------------------ -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in reverse Target.List'Range loop Process (Target.List (I)); end loop; end if; end Reverse_Iterate; -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; -- ------------------------------ -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. -- ------------------------------ function Get (Container : in Vector'Class) return Ref is begin return Container.List.Get; end Get; -- ------------------------------ -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. -- ------------------------------ procedure Append (Container : in out Vector; Item : in Element_Type) is begin Container.List.Append (Item); end Append; -- ------------------------------ -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. -- ------------------------------ procedure Remove (Container : in out Vector; Item : in Element_Type) is begin Container.List.Remove (Item); end Remove; -- Release the vector elements. overriding procedure Finalize (Object : in out Vector) is begin null; end Finalize; -- Vector of objects protected body Protected_Vector is -- ------------------------------ -- Get a readonly reference to the vector. -- ------------------------------ function Get return Ref is begin return Elements; end Get; -- ------------------------------ -- Append the element to the vector. -- ------------------------------ procedure Append (Item : in Element_Type) is New_Items : Vector_Record_Access; Len : Natural; begin if Elements.Target = null then New_Items := new Vector_Record (Len => 1); Len := 1; else Len := Elements.Target.Len + 1; New_Items := new Vector_Record (Len => Len); New_Items.List (1 .. Len - 1) := Elements.Target.List; Finalize (Elements); end if; New_Items.List (Len) := Item; Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end Append; -- ------------------------------ -- Remove the element from the vector. -- ------------------------------ procedure Remove (Item : in Element_Type) is New_Items : Vector_Record_Access; Items : constant Vector_Record_Access := Elements.Target; begin if Items = null then return; end if; for I in Items.List'Range loop if Items.List (I) = Item then if Items.Len = 0 then Finalize (Elements); Elements.Target := null; else New_Items := new Vector_Record (Len => Items.Len - 1); if I > 1 then New_Items.List (1 .. I - 1) := Items.List (1 .. I - 1); end if; if I <= New_Items.List'Last then New_Items.List (I .. New_Items.List'Last) := Items.List (I + 1 .. Items.List'Last); end if; Finalize (Elements); Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end if; return; end if; end loop; end Remove; end Protected_Vector; end Util.Concurrent.Arrays;
----------------------------------------------------------------------- -- Util.Concurrent.Arrays -- Concurrent Arrays -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Arrays is procedure Free is new Ada.Unchecked_Deallocation (Object => Vector_Record, Name => Vector_Record_Access); -- ------------------------------ -- Returns True if the container is empty. -- ------------------------------ function Is_Empty (Container : in Ref) return Boolean is begin return Container.Target = null; end Is_Empty; -- ------------------------------ -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in Target.List'Range loop Process (Target.List (I)); end loop; end if; end Iterate; -- ------------------------------ -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. -- ------------------------------ procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)) is Target : constant Vector_Record_Access := Container.Target; begin if Target /= null then for I in reverse Target.List'Range loop Process (Target.List (I)); end loop; end if; end Reverse_Iterate; -- ------------------------------ -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Ref) is Release : Boolean; begin if Obj.Target /= null then Util.Concurrent.Counters.Decrement (Obj.Target.Ref_Counter, Release); if Release then Free (Obj.Target); else Obj.Target := null; end if; end if; end Finalize; -- ------------------------------ -- Update the reference counter after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Ref) is begin if Obj.Target /= null then Util.Concurrent.Counters.Increment (Obj.Target.Ref_Counter); end if; end Adjust; -- ------------------------------ -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. -- ------------------------------ function Get (Container : in Vector'Class) return Ref is begin return Container.List.Get; end Get; -- ------------------------------ -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. -- ------------------------------ procedure Append (Container : in out Vector; Item : in Element_Type) is begin Container.List.Append (Item); end Append; -- ------------------------------ -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. -- ------------------------------ procedure Remove (Container : in out Vector; Item : in Element_Type) is begin Container.List.Remove (Item); end Remove; -- Release the vector elements. overriding procedure Finalize (Object : in out Vector) is begin null; end Finalize; -- Vector of objects protected body Protected_Vector is -- ------------------------------ -- Get a readonly reference to the vector. -- ------------------------------ function Get return Ref is begin return Elements; end Get; -- ------------------------------ -- Append the element to the vector. -- ------------------------------ procedure Append (Item : in Element_Type) is New_Items : Vector_Record_Access; Len : Natural; begin if Elements.Target = null then New_Items := new Vector_Record (Len => 1); Len := 1; else Len := Elements.Target.Len + 1; New_Items := new Vector_Record (Len => Len); New_Items.List (1 .. Len - 1) := Elements.Target.List; Finalize (Elements); end if; New_Items.List (Len) := Item; Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end Append; -- ------------------------------ -- Remove the element from the vector. -- ------------------------------ procedure Remove (Item : in Element_Type) is New_Items : Vector_Record_Access; Items : constant Vector_Record_Access := Elements.Target; begin if Items = null then return; end if; for I in Items.List'Range loop if Items.List (I) = Item then if Items.Len = 1 then Finalize (Elements); Elements.Target := null; else New_Items := new Vector_Record (Len => Items.Len - 1); if I > 1 then New_Items.List (1 .. I - 1) := Items.List (1 .. I - 1); end if; if I <= New_Items.List'Last then New_Items.List (I .. New_Items.List'Last) := Items.List (I + 1 .. Items.List'Last); end if; Finalize (Elements); Util.Concurrent.Counters.Increment (New_Items.Ref_Counter); Elements.Target := New_Items; end if; return; end if; end loop; end Remove; end Protected_Vector; end Util.Concurrent.Arrays;
Fix removal of last element
Fix removal of last element
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
5fb4451a779f74e32eb8468f2f9dc38772d308fd
regtests/asf-requests-tests.adb
regtests/asf-requests-tests.adb
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with ASF.Requests.Mockup; package body ASF.Requests.Tests is use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Requests.Tests"); package Caller is new Util.Test_Caller (Test, "Requests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header", Test_Split_Header'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales", Test_Accept_Locales'Access); end Add_Tests; -- ------------------------------ -- Test the Split_Header procedure. -- ------------------------------ procedure Test_Split_Header (T : in out Test) is procedure Process_Text (Item : in String; Quality : in Quality_Type); Count : Natural := 0; procedure Process_Text (Item : in String; Quality : in Quality_Type) is begin T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi" or Item = "text/x-c", "Invalid item: " & Item); T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0, "Invalid quality"); if Item = "text/plain" then T.Assert (Quality = 0.5, "Invalid quality for " & Item); elsif Item = "text/x-dvi" or Item = "text/html" then T.Assert (Quality = 0.8, "Invalid quality for " & Item); else T.Assert (Quality = 1.0, "Invalid quality for " & Item); end if; Count := Count + 1; end Process_Text; begin Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c", Process_Text'Access); Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items"); end Test_Split_Header; -- ------------------------------ -- Test the Accept_Locales procedure. -- ------------------------------ procedure Test_Accept_Locales (T : in out Test) is procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type); use Util.Locales; Req : ASF.Requests.Mockup.Request; Count : Natural := 0; procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type) is Lang : constant String := Util.Locales.Get_Language (Locale); begin Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale)); T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en", "Invalid lang: " & Lang); Count := Count + 1; end Process_Locale; begin Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7"); Req.Accept_Locales (Process_Locale'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls"); end Test_Accept_Locales; end ASF.Requests.Tests;
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with ASF.Requests.Mockup; package body ASF.Requests.Tests is use Util.Tests; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Requests.Tests"); package Caller is new Util.Test_Caller (Test, "Requests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Requests.Split_Header", Test_Split_Header'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Accept_Locales", Test_Accept_Locales'Access); end Add_Tests; -- ------------------------------ -- Test the Split_Header procedure. -- ------------------------------ procedure Test_Split_Header (T : in out Test) is procedure Process_Text (Item : in String; Quality : in Quality_Type); Count : Natural := 0; procedure Process_Text (Item : in String; Quality : in Quality_Type) is begin T.Assert (Item = "text/plain" or Item = "text/html" or Item = "text/x-dvi" or Item = "text/x-c", "Invalid item: " & Item); T.Assert (Quality = 0.5 or Quality = 0.8 or Quality = 1.0, "Invalid quality"); if Item = "text/plain" then T.Assert (Quality = 0.5, "Invalid quality for " & Item); elsif Item = "text/x-dvi" or Item = "text/html" then T.Assert (Quality = 0.8, "Invalid quality for " & Item); else T.Assert (Quality = 1.0, "Invalid quality for " & Item); end if; Count := Count + 1; end Process_Text; begin Split_Header ("text/plain; q=0.5, text/html,text/x-dvi; q=0.8, text/x-c", Process_Text'Access); Util.Tests.Assert_Equals (T, 4, Count, "Invalid number of items"); end Test_Split_Header; -- ------------------------------ -- Test the Accept_Locales procedure. -- ------------------------------ procedure Test_Accept_Locales (T : in out Test) is procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type); use Util.Locales; Req : ASF.Requests.Mockup.Request; Count : Natural := 0; procedure Process_Locale (Locale : in Util.Locales.Locale; Quality : in Quality_Type) is pragma Unreferenced (Quality); Lang : constant String := Util.Locales.Get_Language (Locale); begin Log.Info ("Found locale: {0}", Util.Locales.To_String (Locale)); T.Assert (Lang = "da" or Lang = "en_GB" or Lang = "en", "Invalid lang: " & Lang); Count := Count + 1; end Process_Locale; begin Req.Set_Header ("Accept-Language", "da, en-gb;q=0.8, en;q=0.7"); Req.Accept_Locales (Process_Locale'Access); Util.Tests.Assert_Equals (T, 3, Count, "Invalid number of calls"); end Test_Accept_Locales; end ASF.Requests.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
afabb07ac31b2ee2669919fc0f4a109789553353
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 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 null; end Finalize; 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. ----------------------------------------------------------------------- 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 -- ------------------------------ -- 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; -- ------------------------------ -- 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;
Implement the protected procedure Clear to clear all the events and release the block event storage
Implement the protected procedure Clear to clear all the events and release the block event storage
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4b248e4447a401fd23c7a015917f3265bf8d32d0
src/util-measures.adb
src/util-measures.adb
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 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.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; with Util.Streams.Texts.TR; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is use Util.Streams.Buffered; procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Unchecked_Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; use Ada.Calendar; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 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.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; with Util.Streams.Texts.TR; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Unchecked_Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
287f23da2a0b519b455f38aef02616f7d1b6f1b1
regtests/util-texts-builders_tests.adb
regtests/util-texts-builders_tests.adb
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Append", Test_Inline_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Iterate", Test_Inline_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail", Test_Tail'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Inline_Append (T : in out Test) is procedure Append (Into : in out String; Last : out Natural); S : constant String := "0123456789"; I : Positive := S'First; B : String_Builder.Builder (3); procedure Append (Into : in out String; Last : out Natural) is Pos : Natural := Into'First; begin while Pos <= Into'Last and I <= S'Last loop Into (Pos) := S (I); Pos := Pos + 1; I := I + 1; end loop; Last := Pos - 1; end Append; procedure Fill is new String_Builder.Inline_Append (Append); begin Fill (B); Util.Tests.Assert_Equals (T, S'Length, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "0123456789", String_Builder.To_Array (B), "Invalid content"); I := S'First; Fill (B); Util.Tests.Assert_Equals (T, "01234567890123456789", String_Builder.To_Array (B), "Invalid content"); String_Builder.Clear (B); I := S'Last; Fill (B); Util.Tests.Assert_Equals (T, "9", String_Builder.To_Array (B), "Invalid content"); String_Builder.Clear (B); I := S'Last + 1; Fill (B); Util.Tests.Assert_Equals (T, "", String_Builder.To_Array (B), "Invalid content"); end Test_Inline_Append; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the tail operation. -- ------------------------------ procedure Test_Tail (T : in out Test) is procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural); procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural) is P : constant String := "0123456789"; B : String_Builder.Builder (Min); begin for I in 1 .. Max loop String_Builder.Append (B, P (1 + (I mod 10))); end loop; declare S : constant String := String_Builder.Tail (B, L); S2 : constant String := String_Builder.To_Array (B); begin Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length"); if L >= Max then Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result"); else Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S, "Invalid Tail result {" & Positive'Image (Min) & "," & Positive'Image (Max) & "," & Positive'Image (L) & "]"); end if; end; end Check_Tail; begin for I in 1 .. 100 loop for J in 1 .. 8 loop for K in 1 .. I + 3 loop Check_Tail (J, I, K); end loop; end loop; end loop; end Test_Tail; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Inline_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; procedure Get is new String_Builder.Inline_Iterate (Process); begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; Get (B); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Inline_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Append", Test_Inline_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Inline_Iterate", Test_Inline_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail", Test_Tail'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Find", Test_Find'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Inline_Append (T : in out Test) is procedure Append (Into : in out String; Last : out Natural); S : constant String := "0123456789"; I : Positive := S'First; B : String_Builder.Builder (3); procedure Append (Into : in out String; Last : out Natural) is Pos : Natural := Into'First; begin while Pos <= Into'Last and I <= S'Last loop Into (Pos) := S (I); Pos := Pos + 1; I := I + 1; end loop; Last := Pos - 1; end Append; procedure Fill is new String_Builder.Inline_Append (Append); begin Fill (B); Util.Tests.Assert_Equals (T, S'Length, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "0123456789", String_Builder.To_Array (B), "Invalid content"); I := S'First; Fill (B); Util.Tests.Assert_Equals (T, "01234567890123456789", String_Builder.To_Array (B), "Invalid content"); String_Builder.Clear (B); I := S'Last; Fill (B); Util.Tests.Assert_Equals (T, "9", String_Builder.To_Array (B), "Invalid content"); String_Builder.Clear (B); I := S'Last + 1; Fill (B); Util.Tests.Assert_Equals (T, "", String_Builder.To_Array (B), "Invalid content"); end Test_Inline_Append; -- ------------------------------ -- Test the Find generic operation. -- ------------------------------ procedure Test_Find (T : in out Test) is B : String_Builder.Builder (3); function Index (Content : in String) return Natural is begin for I in Content'Range loop if Content (I) = 'b' then return I; end if; end loop; return 0; end Index; function Find is new String_Builder.Find (Index); Pos : Natural; begin String_Builder.Append (B, "ab"); Pos := Find (B, 1); Util.Tests.Assert_Equals (T, 2, Pos, "Invalid find"); String_Builder.Append (B, "deab"); Pos := Find (B, Pos + 1); Util.Tests.Assert_Equals (T, 6, Pos, "Invalid find"); Pos := Find (B, Pos + 1); Util.Tests.Assert_Equals (T, 0, Pos, "Invalid find"); end Test_Find; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the tail operation. -- ------------------------------ procedure Test_Tail (T : in out Test) is procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural); procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural) is P : constant String := "0123456789"; B : String_Builder.Builder (Min); begin for I in 1 .. Max loop String_Builder.Append (B, P (1 + (I mod 10))); end loop; declare S : constant String := String_Builder.Tail (B, L); S2 : constant String := String_Builder.To_Array (B); begin Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length"); if L >= Max then Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result"); else Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S, "Invalid Tail result {" & Positive'Image (Min) & "," & Positive'Image (Max) & "," & Positive'Image (L) & "]"); end if; end; end Check_Tail; begin for I in 1 .. 100 loop for J in 1 .. 8 loop for K in 1 .. I + 3 loop Check_Tail (J, I, K); end loop; end loop; end loop; end Test_Tail; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Inline_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; procedure Get is new String_Builder.Inline_Iterate (Process); begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; Get (B); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Inline_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
Add the Test_Find procedure and register the new test for execution
Add the Test_Find procedure and register the new test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b5aec38a443062349d1c089a36e6e7e175389310
src/mysql/ado-schemas-mysql.adb
src/mysql/ado-schemas-mysql.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 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 ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.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(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" 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 = "decimal" 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.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Col.Size := String_To_Length (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Value := Stmt.Get_Unbounded_String (4); Col.Is_Primary := Value = "PRI"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); 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.Mysql;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2011, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.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(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" then return T_BLOB; elsif Value = "float" then return T_FLOAT; elsif Value = "double" then return T_DOUBLE; 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 = "decimal" 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.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Col.Size := String_To_Length (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Value := Stmt.Get_Unbounded_String (4); Col.Is_Primary := Value = "PRI"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); 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.Mysql;
Fix support for float and double when loading Mysql schema
Fix support for float and double when loading Mysql schema
Ada
apache-2.0
stcarrez/ada-ado
f369523bce6332720fbaf988de4178c98cafed09
src/base/log/util-log-appenders.adb
src/base/log/util-log-appenders.adb
----------------------------------------------------------------------- -- 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.Calendar.Formatting; with Ada.Strings; with Ada.Strings.Fixed; with Util.Strings.Transforms; with Util.Log.Loggers; with Util.Properties.Basic; package body Util.Log.Appenders is use Ada; -- ------------------------------ -- Get the log level that triggers display of the log events -- ------------------------------ function Get_Level (Self : in Appender) return Level_Type is begin return Self.Level; end Get_Level; -- ------------------------------ -- Set the log level. -- ------------------------------ procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type) is Prop_Name : constant String := Name & ".level"; begin if Properties.Exists (Prop_Name) then Self.Level := Get_Level (Properties.Get (Prop_Name), Level); else Self.Level := Level; end if; end Set_Level; -- ------------------------------ -- Set the log layout format. -- ------------------------------ procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type) is use Ada.Strings; use Util.Strings.Transforms; Prop_Name : constant String := Name & ".layout"; begin if Properties.Exists (Prop_Name) then declare Value : constant String := To_Lower_Case (Fixed.Trim (Properties.Get (Prop_Name), Both)); begin if Value = "message" then Self.Layout := MESSAGE; elsif Value = "level-message" then Self.Layout := LEVEL_MESSAGE; elsif Value = "date-level-message" or Value = "level-date-message" then Self.Layout := DATE_LEVEL_MESSAGE; else Self.Layout := FULL; end if; end; else Self.Layout := Layout; end if; end Set_Layout; -- ------------------------------ -- Format the event into a string -- ------------------------------ function Format (Self : in Appender; Event : in Log_Event) return String is begin case Self.Layout is when MESSAGE => return To_String (Event.Message); when LEVEL_MESSAGE => return Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when DATE_LEVEL_MESSAGE => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when FULL => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & " - " & Loggers.Get_Logger_Name (Event.Logger.all) & " - " & To_String (Event.Message); end case; end Format; procedure Append (Self : in out File_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Self.Output, Format (Self, Event)); if Self.Immediate_Flush then Self.Flush; end if; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is begin Text_IO.Flush (Self.Output); end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.Flush; Text_IO.Close (File => Self.Output); end Finalize; -- ------------------------------ -- 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 is use Util.Properties.Basic; Path : constant String := Properties.Get (Name & ".File"); Append : constant Boolean := Boolean_Property.Get (Properties, Name & ".append", True); Result : constant File_Appender_Access := new File_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Set_File (Path, Append); Result.Immediate_Flush := Boolean_Property.Get (Properties, Name & ".immediateFlush", True); return Result.all'Access; end Create_File_Appender; -- ------------------------------ -- 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) is Mode : Text_IO.File_Mode; begin if Append then Mode := Text_IO.Append_File; else Mode := Text_IO.Out_File; end if; Text_IO.Open (File => Self.Output, Name => Path, Mode => Mode); exception when Text_IO.Name_Error => Text_IO.Create (File => Self.Output, Name => Path); end Set_File; procedure Append (Self : in out Console_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Format (Self, Event)); end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out Console_Appender) is pragma Unreferenced (Self); begin Text_IO.Flush; end Flush; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Append (Event); end loop; end Append; -- ------------------------------ -- 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 is Result : constant Console_Appender_Access := new Console_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); return Result.all'Access; end Create_Console_Appender; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out List_Appender) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Flush; end loop; end Flush; -- ------------------------------ -- Add the appender to the list. -- ------------------------------ procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access) is begin if Self.Count < Self.Appenders'Last then Self.Count := Self.Count + 1; Self.Appenders (Self.Count) := Object; end if; end Add_Appender; -- ------------------------------ -- Create a list appender and configure it according to the properties -- ------------------------------ function Create_List_Appender return List_Appender_Access is Result : constant List_Appender_Access := new List_Appender; begin return Result; end Create_List_Appender; 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.Calendar.Formatting; with Ada.Strings; with Ada.Strings.Fixed; with Util.Strings.Transforms; with Util.Log.Loggers; with Util.Properties.Basic; package body Util.Log.Appenders is use Ada; -- ------------------------------ -- Get the log level that triggers display of the log events -- ------------------------------ function Get_Level (Self : in Appender) return Level_Type is begin return Self.Level; end Get_Level; -- ------------------------------ -- Set the log level. -- ------------------------------ procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type) is Prop_Name : constant String := Name & ".level"; begin if Properties.Exists (Prop_Name) then Self.Level := Get_Level (Properties.Get (Prop_Name), Level); else Self.Level := Level; end if; end Set_Level; -- ------------------------------ -- Set the log layout format. -- ------------------------------ procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type) is use Ada.Strings; use Util.Strings.Transforms; Prop_Name : constant String := Name & ".layout"; begin if Properties.Exists (Prop_Name) then declare Value : constant String := To_Lower_Case (Fixed.Trim (Properties.Get (Prop_Name), Both)); begin if Value = "message" then Self.Layout := MESSAGE; elsif Value = "level-message" then Self.Layout := LEVEL_MESSAGE; elsif Value = "date-level-message" or Value = "level-date-message" then Self.Layout := DATE_LEVEL_MESSAGE; else Self.Layout := FULL; end if; end; else Self.Layout := Layout; end if; end Set_Layout; -- ------------------------------ -- Format the event into a string -- ------------------------------ function Format (Self : in Appender; Event : in Log_Event) return String is begin case Self.Layout is when MESSAGE => return To_String (Event.Message); when LEVEL_MESSAGE => return Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when DATE_LEVEL_MESSAGE => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when FULL => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & " - " & Loggers.Get_Logger_Name (Event.Logger.all) & " - " & To_String (Event.Message); end case; end Format; procedure Append (Self : in out File_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Self.Output, Format (Self, Event)); if Self.Immediate_Flush then Self.Flush; end if; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is begin Text_IO.Flush (Self.Output); end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.Flush; Text_IO.Close (File => Self.Output); end Finalize; -- ------------------------------ -- 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 is use Util.Properties.Basic; Path : constant String := Properties.Get (Name & ".File"); Append : constant Boolean := Boolean_Property.Get (Properties, Name & ".append", True); Result : constant File_Appender_Access := new File_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Set_File (Path, Append); Result.Immediate_Flush := Boolean_Property.Get (Properties, Name & ".immediateFlush", True); return Result.all'Access; end Create_File_Appender; -- ------------------------------ -- 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) is Mode : Text_IO.File_Mode; begin if Append then Mode := Text_IO.Append_File; else Mode := Text_IO.Out_File; end if; Text_IO.Open (File => Self.Output, Name => Path, Mode => Mode); exception when Text_IO.Name_Error => Text_IO.Create (File => Self.Output, Name => Path); end Set_File; procedure Append (Self : in out Console_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Self.Output.all, Format (Self, Event)); end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out Console_Appender) is begin Text_IO.Flush (Self.Output.all); end Flush; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Append (Event); end loop; end Append; -- ------------------------------ -- 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 is use Util.Properties.Basic; Result : constant Console_Appender_Access := new Console_Appender; Stderr : constant Boolean := Boolean_Property.Get (Properties, Name & ".stderr", False); begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Output := (if Stderr then Text_IO.Standard_Error else Text_IO.Standard_Output); return Result.all'Access; end Create_Console_Appender; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out List_Appender) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Flush; end loop; end Flush; -- ------------------------------ -- Add the appender to the list. -- ------------------------------ procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access) is begin if Self.Count < Self.Appenders'Last then Self.Count := Self.Count + 1; Self.Appenders (Self.Count) := Object; end if; end Add_Appender; -- ------------------------------ -- Create a list appender and configure it according to the properties -- ------------------------------ function Create_List_Appender return List_Appender_Access is Result : constant List_Appender_Access := new List_Appender; begin return Result; end Create_List_Appender; end Util.Log.Appenders;
Update the console appender to write the message on standard output or standard error
Update the console appender to write the message on standard output or standard error
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e6796a79896910a2b23b698d7e131ef7c0101b44
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Get the list of role names that are defined by the role map. -- ------------------------------ function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array is Result : Role_Name_Array (1 .. Get_Count (Map)); Pos : Positive := 1; begin for Role in Map'Range loop if Map (Role) then Result (Pos) := Manager.Names (Role); Pos := Pos + 1; end if; end loop; return Result; end Get_Role_Names; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Get the number of roles set in the map. -- ------------------------------ function Get_Count (Map : in Role_Map) return Natural is Count : Natural := 0; begin for R of Map loop if R then Count := Count + 1; end if; end loop; return Count; end Get_Count; -- ------------------------------ -- Get the list of role names that are defined by the role map. -- ------------------------------ function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array is Result : Role_Name_Array (1 .. Get_Count (Map)); Pos : Positive := 1; begin for Role in Map'Range loop if Map (Role) then Result (Pos) := Manager.Names (Role); Pos := Pos + 1; end if; end loop; return Result; end Get_Role_Names; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Implement the Get_Count function
Implement the Get_Count function
Ada
apache-2.0
stcarrez/ada-security
4b6cebc02762223a1d7ec675bd20f92ec9fafc53
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Modules.Get; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Wikis.Beans; with AWA.Modules.Beans; with ADO.Sessions; with Util.Log.Loggers; package body AWA.Wikis.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module"); package Register is new AWA.Modules.Beans (Module => Wiki_Module, Module_Access => Wiki_Module_Access); -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wikis module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Wikis.Beans.Wiki_Space_Bean", Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the wikis module. -- ------------------------------ function Get_Wiki_Module return Wiki_Module_Access is function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME); begin return Get; end Get_Wiki_Module; -- ------------------------------ -- Create the wiki space. -- ------------------------------ procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is pragma Unreferenced (Module); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name)); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission, Entity => WS); Wiki.Set_Workspace (WS); Wiki.Save (DB); -- Add the permission for the user to use the new wiki space. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Wiki); Ctx.Commit; Log.Info ("Wiki {0} created for user {1}", ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User)); end Create_Wiki_Space; -- ------------------------------ -- Save the wiki space. -- ------------------------------ procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name)); Ctx.Start; -- Check that the user has the update permission on the given wiki space. AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission, Entity => Wiki); Wiki.Save (DB); Ctx.Commit; end Save_Wiki_Space; -- ------------------------------ -- Load the wiki space. -- ------------------------------ procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Module); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Wiki.Load (DB, Id, Found); end Load_Wiki_Space; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Modules.Get; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Wikis.Beans; with AWA.Modules.Beans; with ADO.Sessions; with Util.Log.Loggers; package body AWA.Wikis.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module"); package Register is new AWA.Modules.Beans (Module => Wiki_Module, Module_Access => Wiki_Module_Access); -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wikis module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Wikis.Beans.Wiki_Space_Bean", Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the wikis module. -- ------------------------------ function Get_Wiki_Module return Wiki_Module_Access is function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME); begin return Get; end Get_Wiki_Module; -- ------------------------------ -- Create the wiki space. -- ------------------------------ procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is pragma Unreferenced (Module); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name)); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission, Entity => WS); Wiki.Set_Workspace (WS); Wiki.Save (DB); -- Add the permission for the user to use the new wiki space. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Wiki); Ctx.Commit; Log.Info ("Wiki {0} created for user {1}", ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User)); end Create_Wiki_Space; -- ------------------------------ -- Save the wiki space. -- ------------------------------ procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name)); Ctx.Start; -- Check that the user has the update permission on the given wiki space. AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission, Entity => Wiki); Wiki.Save (DB); Ctx.Commit; end Save_Wiki_Space; -- ------------------------------ -- Load the wiki space. -- ------------------------------ procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Module); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Wiki.Load (DB, Id, Found); end Load_Wiki_Space; -- ------------------------------ -- Create the wiki page into the wiki space. -- ------------------------------ procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Log.Info ("Create wiki page {0}", String '(Page.Get_Name)); -- Check that the user has the create wiki page permission on the given wiki space. AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission, Entity => Into); Ctx.Start; Page.Set_Wiki (Into); Page.Save (DB); Ctx.Commit; end Create_Wiki_Page; -- ------------------------------ -- Save the wiki page. -- ------------------------------ procedure Save (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin -- Check that the user has the create wiki page permission on the given wiki space. AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission, Entity => Page); Ctx.Start; Page.Save (DB); Ctx.Commit; end Save; end AWA.Wikis.Modules;
Implement the Create_Wiki_Page and Save operations
Implement the Create_Wiki_Page and Save operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
15a46090dfa65542574f44fc3b9311c2b48b324d
regtests/util-serialize-io-json-tests.adb
regtests/util-serialize-io-json-tests.adb
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); end Test_Parser; end Util.Serialize.IO.JSON.Tests;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); end Test_Parser; end Util.Serialize.IO.JSON.Tests;
Add a test case for json
Add a test case for json
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
327d09ea699e2a18d4d9b729646fa2f1e28bfe4a
regtests/util-serialize-io-json-tests.ads
regtests/util-serialize-io-json-tests.ads
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Serialize.IO.JSON.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Parse_Error (T : in out Test); procedure Test_Parser (T : in out Test); -- Generate some output stream for the test. procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class); -- Test the JSON output stream generation. procedure Test_Output (T : in out Test); end Util.Serialize.IO.JSON.Tests;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Serialize.IO.JSON.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Parse_Error (T : in out Test); procedure Test_Parser (T : in out Test); -- Generate some output stream for the test. procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class); -- Test the JSON output stream generation. procedure Test_Output (T : in out Test); -- Test reading a JSON content into an Object tree. procedure Test_Read (T : in out Test); end Util.Serialize.IO.JSON.Tests;
Declare the Test_Read procedure
Declare the Test_Read procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2cdcaa54fe3ea4bc2e6c90b11049987dbb7ef5b4
awa/plugins/awa-images/src/awa-images-services.adb
awa/plugins/awa-images/src/awa-images-services.adb
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (File); Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare use Ada.Strings; Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (File); Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Service); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e9b9440c4df776b5d2b54f48c6a460024e622a42
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Create a new blog. procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Post : AWA.Blogs.Models.Post_Ref; Blog_Id : ADO.Identifier; Title : Ada.Strings.Unbounded.Unbounded_String; Text : Ada.Strings.Unbounded.Unbounded_String; URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create a new post. procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. procedure Delete_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Admin_Post_List_Bean bean instance. function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_List_Bean bean instance. function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- 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.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Admin_Post_List_Bean bean instance. function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_List_Bean bean instance. function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
Use the UML generated Ada bean - implement the Save and Delete operations defined by the UML model - simplify the implementation
Use the UML generated Ada bean - implement the Save and Delete operations defined by the UML model - simplify the implementation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
091c49ae25cfc10c4918c0054d63ac935634b79b
src/babel_main.adb
src/babel_main.adb
with GNAT.IO; use GNAT.IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Util.Log.Loggers; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; with Babel.Base.Text; with Babel.Base.Users; with Babel.Streams; with Babel.Streams.XZ; with Babel.Streams.Cached; with Babel.Streams.Files; with Tar; procedure babel_main is use Ada.Strings.Unbounded; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; Database : aliased Babel.Base.Text.Text_Database; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Do_Backup (Count : in Positive) is Workers : Babel.Strategies.Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access); Backup.Scan (Queue, Container); end Do_Backup; begin Util.Log.Loggers.Initialize ("babel.properties"); Dir := Babel.Files.Allocate (Name => ".", Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Store.Set_Root_Directory ("/tmp/babel-store"); Local.Set_Root_Directory ("."); Backup.Set_Filters (Exclude'Unchecked_Access); Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Backup.Set_Buffers (Buffers'Unchecked_Access); Backup.Set_Database (Database'Unchecked_Access); Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size)); Do_Backup (2); Database.Save ("database.txt"); -- Bkp.Files.Scan (".", Dir); -- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access); -- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size)); -- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files)); -- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs)); end babel_main;
with GNAT.Command_Line; use GNAT.Command_Line; with GNAT.IO; use GNAT.IO; with GNAT.Traceback.Symbolic; with Ada.Exceptions; with Ada.Command_Line; with Ada.Text_IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Util.Log.Loggers; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; with Babel.Base.Text; with Babel.Base.Users; with Babel.Streams; with Babel.Streams.XZ; with Babel.Streams.Cached; with Babel.Streams.Files; with Tar; procedure babel_main is use Ada.Strings.Unbounded; Out_Dir : Ada.Strings.Unbounded.Unbounded_String; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; Database : aliased Babel.Base.Text.Text_Database; Queue : aliased Babel.Files.Queues.File_Queue; Debug : Boolean := False; Task_Count : Positive := 2; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Usage is begin Ada.Text_IO.Put_Line ("babel [-d] [-t count] {command} [options]"); Ada.Text_IO.Put_Line (" -d Debug mode"); Ada.Text_IO.Put_Line (" -t count Number of tasks to create"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Commands:"); Ada.Text_IO.Put_Line (" copy <dst-dir> <src-dir>"); Ada.Text_IO.Put_Line (" scan <src-dir>"); Ada.Command_Line.Set_Exit_Status (2); end Usage; procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is begin Strategy.Set_Filters (Exclude'Unchecked_Access); Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Strategy.Set_Buffers (Buffers'Unchecked_Access); Strategy.Set_Database (Database'Unchecked_Access); Strategy.Set_Queue (Queue'Unchecked_Access); end Configure; package Backup_Workers is new Babel.Strategies.Workers (Babel.Strategies.Default.Default_Strategy_Type); procedure Do_Backup (Count : in Positive) is Workers : Backup_Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Configure (Backup); Backup_Workers.Configure (Workers, Configure'Access); Backup_Workers.Start (Workers); Backup.Scan (Queue, Container); Backup_Workers.Finish (Workers, Database); end Do_Backup; procedure Do_Copy is Dst : constant String := GNAT.Command_Line.Get_Argument; Src : constant String := GNAT.Command_Line.Get_Argument; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); -- Exclude.Add_Exclude (".svn"); -- Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 20_000_000); Store.Set_Root_Directory (Dst); Local.Set_Root_Directory (""); Do_Backup (Task_Count); Database.Save ("database.txt"); end Do_Copy; procedure Do_Scan is Src : constant String := GNAT.Command_Line.Get_Argument; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Local.Set_Root_Directory (Src); Do_Backup (Task_Count); Database.Save ("database.txt"); end Do_Scan; begin Util.Log.Loggers.Initialize ("babel.properties"); Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v o: t:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 'd' => Debug := True; when 't' => Task_Count := Positive'Value (Parameter); when '*' => exit; when others => null; end case; end loop; if Ada.Command_Line.Argument_Count = 0 then Usage; return; end if; declare Cmd_Name : constant String := Full_Switch; begin if Cmd_Name = "copy" then Do_Copy; elsif Cmd_Name = "scan" then Do_Scan; else Usage; end if; end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Usage; 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 babel_main;
Add a copy/scan command with some configuration options
Add a copy/scan command with some configuration options
Ada
apache-2.0
stcarrez/babel
0e16f5ab0a751c80034ab883f5473013e81747b1
mat/src/mat-targets-readers.adb
mat/src/mat-targets-readers.adb
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); For_Servant.Process.Events := For_Servant.Events; MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); For_Servant.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_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 begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Process_Reader.Events := Reader.Get_Target_Events; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); For_Servant.Process.Events := For_Servant.Events; MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; Heap : MAT.Memory.Region_Info; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); For_Servant.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_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 begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Process_Reader.Events := Reader.Get_Target_Events; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
Update calls to MAT.Readers.Marshaller.Get_xxx operation
Update calls to MAT.Readers.Marshaller.Get_xxx operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
edac66203d175a7192db1e4098c05b0fe7967dd6
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Principals; with ASF.Tests; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ overriding procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Signup_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); Password_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ? AND o.kind = ?"); Query.Bind_Param (1, Email); Query.Bind_Param (2, Signup_Kind); Key.Find (DB, Query, Found); if not Found then Query.Bind_Param (2, Password_Kind); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- ------------------------------ -- Simulate a user login in the given service context. -- ------------------------------ procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request'Class) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; -- ------------------------------ -- Simulate the recovery password process for the given user. -- ------------------------------ procedure Recover_Password (Email : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid redirect after lost password"); end if; -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); if not Key.Is_Null then Log.Error ("There is no access key associated with the user"); end if; -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid response"); end if; -- Check that the user is logged and we have a user principal now. if Request.Get_User_Principal = null then Log.Error ("A user principal should be defined"); end if; end; end Recover_Password; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Principals; with ASF.Tests; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ overriding procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email, Key, True); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email, Key, True); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Signup_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); Password_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ? AND o.kind = ?"); Query.Bind_Param (1, Email); Query.Bind_Param (2, Signup_Kind); Key.Find (DB, Query, Found); if not Found then Query.Bind_Param (2, Password_Kind); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- ------------------------------ -- Simulate a user login in the given service context. -- ------------------------------ procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request'Class) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; -- ------------------------------ -- Simulate the recovery password process for the given user. -- ------------------------------ procedure Recover_Password (Email : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid redirect after lost password"); end if; -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); if not Key.Is_Null then Log.Error ("There is no access key associated with the user"); end if; -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid response"); end if; -- Check that the user is logged and we have a user principal now. if Request.Get_User_Principal = null then Log.Error ("A user principal should be defined"); end if; end; end Recover_Password; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
Update calls to Create_User
Update calls to Create_User
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d4307ed10cdcd590ef61eb2da8b2a844aebc9522
src/gen-commands-templates.adb
src/gen-commands-templates.adb
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with GNAT.Command_Line; with Gen.Artifacts; with Util.Log.Loggers; with Util.Files; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use Util.Log; use GNAT.Command_Line; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates"); -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter)); Util.Strings.Sets.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- 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.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Streams.Stream_IO; with GNAT.Command_Line; with Gen.Artifacts; with EL.Contexts.Default; with EL.Expressions; with EL.Variables.Default; with Util.Log.Loggers; with Util.Files; with Util.Streams.Files; with Util.Streams.Texts; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use GNAT.Command_Line; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates"); -- Apply the patch instruction procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch); function Match_Line (Line : in String; Pattern : in String) return Boolean; -- ------------------------------ -- Check if the line matches the pseudo pattern. -- ------------------------------ function Match_Line (Line : in String; Pattern : in String) return Boolean is L_Pos : Natural := Line'First; P_Pos : Natural := Pattern'First; begin while P_Pos <= Pattern'Last loop if L_Pos > Line'Last then return False; end if; if Line (L_Pos) = Pattern (P_Pos) then if Pattern (P_Pos) /= ' ' then P_Pos := P_Pos + 1; end if; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Pattern (P_Pos + 1) = '*' then P_Pos := P_Pos + 1; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then L_Pos := L_Pos + 1; else return False; end if; end loop; return True; end Match_Line; -- ------------------------------ -- Apply the patch instruction -- ------------------------------ procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch) is procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String) is type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE); Output_Dir : constant String := H.Get_Result_Directory; Path : constant String := Util.Files.Compose (Output_Dir, File); Tmp_File : constant String := Path & ".tmp"; Line_Number : Natural := 0; After_Pos : Natural := 1; Current_State : State := MATCH_AFTER; Tmp_Output : aliased Util.Streams.Files.File_Stream; Output : Util.Streams.Texts.Print_Stream; procedure Process (Line : in String); procedure Process (Line : in String) is begin Line_Number := Line_Number + 1; case Current_State is when MATCH_AFTER => if Match_Line (Line, Info.After.Element (After_Pos)) then Log.Info ("Match after at line {0}", Natural'Image (Line_Number)); After_Pos := After_Pos + 1; if After_Pos >= Natural (Info.After.Length) then Current_State := MATCH_BEFORE; end if; end if; when MATCH_BEFORE => if Match_Line (Line, To_String (Info.Before)) then Log.Info ("Match before at line {0}", Natural'Image (Line_Number)); Log.Info ("Add content {0}", Content); Output.Write (Content); Current_State := MATCH_DONE; end if; when MATCH_DONE => null; end case; Output.Write (Line); Output.Write (ASCII.LF); end Process; begin Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File); Output.Initialize (Tmp_Output'Unchecked_Access); Util.Files.Read_File (Path, Process'Access); Output.Close; if Current_State /= MATCH_DONE then H.Error ("Patch {0} failed", Path); Ada.Directories.Delete_File (Tmp_File); else Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => Tmp_File, New_Name => Path); end if; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Cannot patch file {0}", Path); end Save_Output; begin Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, To_String (Info.Template), Save_Output'Access); end Patch_File; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter), Gen.Generator.Save_Content'Access); Util.Strings.Sets.Next (Iter); end loop; end; -- Apply the patch instructions defined for the command. declare Iter : Patch_Vectors.Cursor := Cmd.Patches.First; begin while Patch_Vectors.Has_Element (Iter) loop Patch_File (Generator, Patch_Vectors.Element (Iter)); Patch_Vectors.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_PATCH, FIELD_AFTER, FIELD_BEFORE, FIELD_INSERT_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; Info : Patch; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; when FIELD_INSERT_TEMPLATE => Closure.Info.Template := To_Unbounded_String (Value); when FIELD_AFTER => Closure.Info.After.Append (To_String (Value)); when FIELD_BEFORE => Closure.Info.Before := To_Unbounded_String (Value); when FIELD_PATCH => Closure.Command.Patches.Append (Closure.Info); Closure.Info.After.Clear; Closure.Info.Before := To_Unbounded_String (""); end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER); Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
Implement some basic support to patch files and insert some template generation content in existing files
Implement some basic support to patch files and insert some template generation content in existing files
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
0ec57fdd135f6521c3c3e1a3c110f993025c76af
src/util-concurrent-arrays.ads
src/util-concurrent-arrays.ads
----------------------------------------------------------------------- -- Util.Concurrent.Arrays -- Concurrent Arrays -- 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.Finalization; with Util.Concurrent.Counters; -- == Introduction == -- The <b>Util.Concurrent.Arrays</b> generic package defines an array which provides a -- concurrent read only access and a protected exclusive write access. This implementation -- is intended to be used in applications that have to frequently iterate over the array -- content. Adding or removing elements in the array is assumed to be a not so frequent -- operation. Based on these assumptions, updating the array is implemented by -- using the <tt>copy on write</tt> design pattern. Read access is provided through a -- reference object that can be shared by multiple readers. -- -- == Declaration == -- The package must be instantiated using the element type representing the array element. -- -- package My_Array is new Util.Concurrent.Arrays (Element_Type => Integer); -- -- == Adding Elements == -- The vector instance is declared and elements are added as follows: -- -- C : My_Array.Vector; -- -- C.Append (E1); -- -- == Iterating over the array == -- To read and iterate over the vector, a task will get a reference to the vector array -- and it will iterate over it. The reference will be held until the reference object is -- finalized. While doing so, if another task updates the vector, a new vector array will -- be associated with the vector instance (but this will not change the reader's references). -- -- R : My_Array.Ref := C.Get; -- -- R.Iterate (Process'Access); -- ... -- R.Iterate (Process'Access); -- -- In the above example, the two `Iterate` operations will iterate over the same list of -- elements, even if another task appends an element in the middle. -- -- Notes: -- * This package is close to the Java class `java.util.concurrent.CopyOnWriteArrayList`. -- -- * The package implements voluntarily a very small subset of `Ada.Containers.Vectors`. -- -- * The implementation does not use the Ada container for performance and size reasons. -- -- * The `Iterate` and `Reverse_Iterate` operation give a direct access to the element. generic type Element_Type is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; package Util.Concurrent.Arrays is -- The reference to the read-only vector elements. type Ref is tagged private; -- Returns True if the container is empty. function Is_Empty (Container : in Ref) return Boolean; -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)); -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)); -- Vector of elements. type Vector is new Ada.Finalization.Limited_Controlled with private; -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. function Get (Container : in Vector'Class) return Ref; -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. procedure Append (Container : in out Vector; Item : in Element_Type); -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. procedure Remove (Container : in out Vector; Item : in Element_Type); -- Release the vector elements. overriding procedure Finalize (Object : in out Vector); private -- To store the vector elements, we use an array which is allocated dynamically. -- The generated code is smaller compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; type Vector_Record (Len : Positive) is record Ref_Counter : Util.Concurrent.Counters.Counter; List : Element_Array (1 .. Len); end record; type Vector_Record_Access is access all Vector_Record; type Ref is new Ada.Finalization.Controlled with record Target : Vector_Record_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); -- Vector of objects protected type Protected_Vector is -- Get a readonly reference to the vector. function Get return Ref; -- Append the element to the vector. procedure Append (Item : in Element_Type); -- Remove the element from the vector. procedure Remove (Item : in Element_Type); private Elements : Ref; end Protected_Vector; type Vector is new Ada.Finalization.Limited_Controlled with record List : Protected_Vector; end record; end Util.Concurrent.Arrays;
----------------------------------------------------------------------- -- util-concurrent-arrays -- Concurrent Arrays -- 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 Ada.Finalization; with Util.Concurrent.Counters; -- == Introduction == -- The <b>Util.Concurrent.Arrays</b> generic package defines an array which provides a -- concurrent read only access and a protected exclusive write access. This implementation -- is intended to be used in applications that have to frequently iterate over the array -- content. Adding or removing elements in the array is assumed to be a not so frequent -- operation. Based on these assumptions, updating the array is implemented by -- using the <tt>copy on write</tt> design pattern. Read access is provided through a -- reference object that can be shared by multiple readers. -- -- == Declaration == -- The package must be instantiated using the element type representing the array element. -- -- package My_Array is new Util.Concurrent.Arrays (Element_Type => Integer); -- -- == Adding Elements == -- The vector instance is declared and elements are added as follows: -- -- C : My_Array.Vector; -- -- C.Append (E1); -- -- == Iterating over the array == -- To read and iterate over the vector, a task will get a reference to the vector array -- and it will iterate over it. The reference will be held until the reference object is -- finalized. While doing so, if another task updates the vector, a new vector array will -- be associated with the vector instance (but this will not change the reader's references). -- -- R : My_Array.Ref := C.Get; -- -- R.Iterate (Process'Access); -- ... -- R.Iterate (Process'Access); -- -- In the above example, the two `Iterate` operations will iterate over the same list of -- elements, even if another task appends an element in the middle. -- -- Notes: -- * This package is close to the Java class `java.util.concurrent.CopyOnWriteArrayList`. -- -- * The package implements voluntarily a very small subset of `Ada.Containers.Vectors`. -- -- * The implementation does not use the Ada container for performance and size reasons. -- -- * The `Iterate` and `Reverse_Iterate` operation give a direct access to the element. generic type Element_Type is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; package Util.Concurrent.Arrays is -- The reference to the read-only vector elements. type Ref is tagged private; -- Returns True if the container is empty. function Is_Empty (Container : in Ref) return Boolean; -- Iterate over the vector elements and execute the <b>Process</b> procedure -- with the element as parameter. procedure Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)); -- Iterate over the vector elements in reverse order and execute the <b>Process</b> procedure -- with the element as parameter. procedure Reverse_Iterate (Container : in Ref; Process : not null access procedure (Item : in Element_Type)); -- Vector of elements. type Vector is new Ada.Finalization.Limited_Controlled with private; -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. function Get (Container : in Vector'Class) return Ref; -- Append the element to the vector. The modification will not be visible to readers -- until they call the <b>Get</b> function. procedure Append (Container : in out Vector; Item : in Element_Type); -- Remove the element represented by <b>Item</b> from the vector. The modification will -- not be visible to readers until they call the <b>Get</b> function. procedure Remove (Container : in out Vector; Item : in Element_Type); -- Release the vector elements. overriding procedure Finalize (Object : in out Vector); private -- To store the vector elements, we use an array which is allocated dynamically. -- The generated code is smaller compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; type Vector_Record (Len : Positive) is record Ref_Counter : Util.Concurrent.Counters.Counter; List : Element_Array (1 .. Len); end record; type Vector_Record_Access is access all Vector_Record; type Ref is new Ada.Finalization.Controlled with record Target : Vector_Record_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); -- Vector of objects protected type Protected_Vector is -- Get a readonly reference to the vector. function Get return Ref; -- Append the element to the vector. procedure Append (Item : in Element_Type); -- Remove the element from the vector. procedure Remove (Item : in Element_Type); private Elements : Ref; end Protected_Vector; type Vector is new Ada.Finalization.Limited_Controlled with record List : Protected_Vector; end record; end Util.Concurrent.Arrays;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e339fa8292b294325975c0b35439d12212445e88
src/el-beans.ads
src/el-beans.ads
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; end EL.Beans;
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is interface and Readonly_Bean; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Get the element at the given index. function Get_Row (From : List_Bean; Index : Natural) return EL.Objects.Object is abstract; end EL.Beans;
Declare the List_Bean to represent lists that can be accessed from the Object
Declare the List_Bean to represent lists that can be accessed from the Object
Ada
apache-2.0
Letractively/ada-el
7a3ddb65ff13d8488162a56af4fa6cdd62a152aa
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENTITY_TYPE => return "entity_type"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Add T_ENTITY_TYPE in the enumeration
Add T_ENTITY_TYPE in the enumeration
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d8ef3d7fce572d55dceecef880e45bcde13f12fc
src/wiki-buffers.adb
src/wiki-buffers.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Buffers is subtype Input is Wiki.Strings.WString; subtype Block_Access is Buffer_Access; procedure Next (Content : in out Buffer_Access; Pos : in out Positive) is begin if Pos + 1 > Content.Last then Content := Content.Next_Block; Pos := 1; else Pos := Pos + 1; end if; end Next; -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Buffer (Size); else B.Next_Block := new Buffer (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive) is Block : Buffer_Access := Buffer; Pos : Positive := From; First : Positive := From; begin while Block /= null loop Append (Into, Block.Content (First .. Block.Last)); Block := Block.Next_Block; Pos := 1; First := 1; end loop; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; procedure Inline_Update (Source : in out Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Update; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Buffer := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural is Count : Natural := 0; Current : Buffer_Access := Buffer; Pos : Positive := From; begin while Current /= null loop declare First : Positive := Pos; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; return Count; end Count_Occurence; procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar) is Pos : Positive := From; begin while Buffer /= null loop declare Last : constant Natural := Buffer.Last; begin while Pos <= Last loop if Buffer.Content (Pos) = Item then From := Pos; return; end if; Pos := Pos + 1; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop; end Find; end Wiki.Buffers;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Buffers is subtype Input is Wiki.Strings.WString; subtype Block_Access is Buffer_Access; procedure Next (Content : in out Buffer_Access; Pos : in out Positive) is begin if Pos + 1 > Content.Last then Content := Content.Next_Block; Pos := 1; else Pos := Pos + 1; end if; end Next; -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Buffer (Size); else B.Next_Block := new Buffer (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Buffer (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. -- ------------------------------ procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive) is begin if From <= Content.First.Last then if To <= Content.First.Last then Append (Into, Content.First.Content (From .. To)); return; end if; Append (Into, Content.First.Content (From .. Content.First.Last)); end if; declare Pos : Integer := From - Into.First.Last; Last : Integer := To - Into.First.Last; B : Block_Access := Into.First.Next_Block; begin loop if B = null then return; end if; if Pos <= B.Last then if Last <= B.Last then Append (Into, B.Content (1 .. Last)); return; end if; Append (Into, B.Content (1 .. B.Last)); end if; Pos := Pos - B.Last; Last := Last - B.Last; B := B.Next_Block; end loop; end; end Append; procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive) is Block : Buffer_Access := Buffer; Pos : Positive := From; First : Positive := From; begin while Block /= null loop Append (Into, Block.Content (First .. Block.Last)); Block := Block.Next_Block; Pos := 1; First := 1; end loop; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Buffer, Name => Buffer_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; procedure Inline_Update (Source : in out Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Update; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Buffer := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural is Count : Natural := 0; Current : Buffer_Access := Buffer; Pos : Positive := From; begin while Current /= null loop declare First : Positive := Pos; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; return Count; end Count_Occurence; procedure Count_Occurence (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar; Count : out Natural) is Current : Buffer_Access := Buffer; Pos : Positive := From; begin Count := 0; while Current /= null loop declare First : Positive := From; Last : Natural := Current.Last; begin while Pos <= Last and then Current.Content (Pos) = Item loop Pos := Pos + 1; end loop; if Pos > First then Count := Count + Pos - First; end if; exit when Pos <= Last; end; Current := Current.Next_Block; Pos := 1; end loop; Buffer := Current; From := Pos; end Count_Occurence; procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar) is Pos : Positive := From; begin while Buffer /= null loop declare Last : constant Natural := Buffer.Last; begin while Pos <= Last loop if Buffer.Content (Pos) = Item then From := Pos; return; end if; Pos := Pos + 1; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop; end Find; end Wiki.Buffers;
Implement the Count_Occurence procedure
Implement the Count_Occurence procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3ca24102ce89b8b584566cc83d2d3e1f3162a20e
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a punctuation character. function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); -- Find the position of the first non space character in the text starting at the -- given position. Returns Text'Last + 1 if the text only contains spaces. function Skip_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Positive; end Wiki.Helpers;
Add Skip_Spaces and Is_Punctuation
Add Skip_Spaces and Is_Punctuation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
874dfa9caae4b901e6252b1d36483c2d9f18a422
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited Interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bcb17c26e15d592d4c78cc69c4b56d44c845ca73
regtests/util-http-clients-tests.adb
regtests/util-http-clients-tests.adb
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Http.Tools; with Util.Strings; with Util.Log.Loggers; package body Util.Http.Clients.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests"); package body Http_Tests is package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get", Test_Http_Get'Access); Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post", Test_Http_Post'Access); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; end if; Log.Info ("Received: {0}", L); end Process_Line; -- ------------------------------ -- Get the test server base URI. -- ------------------------------ function Get_Uri (T : in Test) return String is begin return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port); end Get_Uri; -- ------------------------------ -- Test the http Get operation. -- ------------------------------ procedure Test_Http_Get (T : in out Test) is Request : Client; Reply : Response; begin Request.Get ("http://www.google.com", Reply); T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid: " & 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; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 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 & ".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); end Add_Tests; overriding procedure Set_Up (T : in out Http_Test) is begin Test (T).Set_Up; Register; end Set_Up; end Http_Tests; overriding procedure Set_Up (T : in out Test) is begin Log.Info ("Starting test server"); T.Server := new Test_Server; T.Server.Start; end Set_Up; overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Test_Server'Class, Name => Test_Server_Access); begin if T.Server /= null then Log.Info ("Stopping test server"); T.Server.Stop; Free (T.Server); T.Server := null; end if; end Tear_Down; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is L : constant String := Ada.Strings.Unbounded.To_String (Line); Pos : Natural := Util.Strings.Index (L, ' '); begin if Pos > 0 and Into.Method = UNKNOWN then if L (L'First .. Pos - 1) = "GET" then Into.Method := GET; elsif L (L'First .. Pos - 1) = "POST" then Into.Method := POST; elsif L (L'First .. Pos - 1) = "PUT" then Into.Method := PUT; elsif L (L'First .. Pos - 1) = "DELETE" then Into.Method := DELETE; else Into.Method := UNKNOWN; end if; end if; Pos := Util.Strings.Index (L, ':'); if Pos > 0 then if L (L'First .. Pos) = "Content-Type:" then Into.Content_Type := Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2)); elsif L (L'First .. Pos) = "Content-Length:" then Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2)); end if; end if; if L'Length = 2 and then Into.Length > 0 then for I in 1 .. Into.Length loop declare C : Character; begin Stream.Read (C); Ada.Strings.Unbounded.Append (Into.Result, C); end; end loop; declare Output : Util.Streams.Texts.Print_Stream; begin Output.Initialize (Client'Unchecked_Access); Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF); Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF); Output.Write (ASCII.CR & ASCII.LF); Output.Write ("OK" & ASCII.CR & ASCII.LF); Output.Flush; end; 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); 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; -- Check one header. declare Content : constant String := Reply.Get_Header ("Content-Type"); begin T.Assert (Content'Length > 0, "Empty Content-Type header"); Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type"); end; end Test_Http_Get; -- ------------------------------ -- Test the http POST operation. -- ------------------------------ procedure Test_Http_Post (T : in out Test) is Request : Client; Reply : Response; Uri : constant String := T.Get_Uri; begin Log.Info ("Post on " & Uri); T.Server.Method := UNKNOWN; Request.Post (Uri & "/post", "p1=1", Reply); T.Assert (T.Server.Method = POST, "Invalid method received by server"); Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type, "Invalid content type received by server"); Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response"); Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True); end Test_Http_Post; -- ------------------------------ -- 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.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 (2.0); 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; end Util.Http.Clients.Tests;
Add Test_Http_Put and Test_Http_Delete
Add Test_Http_Put and Test_Http_Delete
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
827420a092460d85a4a0658ee5be43f50c87e186
regtests/util-http-cookies-tests.adb
regtests/util-http-cookies-tests.adb
----------------------------------------------------------------------- -- util-http-cookies-tests - Unit tests for Cookies -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Ada.Strings.Fixed; with Ada.Unchecked_Deallocation; package body Util.Http.Cookies.Tests is use Ada.Strings.Fixed; use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests"); procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access); package Caller is new Util.Test_Caller (Test, "Cookies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie", Test_Create_Cookie'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header", Test_To_Http_Header'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies", Test_Parse_Http_Header'Access); end Add_Tests; -- ------------------------------ -- Test creation of cookie -- ------------------------------ procedure Test_Create_Cookie (T : in out Test) is C : constant Cookie := Create ("cookie", "value"); begin T.Assert_Equals ("cookie", Get_Name (C), "Invalid name"); T.Assert_Equals ("value", Get_Value (C), "Invalid value"); T.Assert (not Is_Secure (C), "Invalid is_secure"); end Test_Create_Cookie; -- ------------------------------ -- Test conversion of cookie for HTTP header -- ------------------------------ procedure Test_To_Http_Header (T : in out Test) is procedure Test_Cookie (C : in Cookie); procedure Test_Cookie (Name : in String; Value : in String); procedure Test_Cookie (C : in Cookie) is S : constant String := To_Http_Header (C); begin Log.Info ("Cookie {0}: {1}", Get_Name (C), S); T.Assert (S'Length > 0, "Invalid cookie length for: " & S); T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S); end Test_Cookie; procedure Test_Cookie (Name : in String; Value : in String) is C : Cookie := Create (Name, Value); begin Test_Cookie (C); for I in 1 .. 24 loop Set_Max_Age (C, I * 3600 + I); Test_Cookie (C); end loop; Set_Secure (C, True); Test_Cookie (C); Set_Http_Only (C, True); Test_Cookie (C); Set_Domain (C, "world.com"); Test_Cookie (C); Set_Path (C, "/some-path"); Test_Cookie (C); end Test_Cookie; begin Test_Cookie ("a", "b"); Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1"); Test_Cookie ("p_41_zy", ""); Test_Cookie ("p_34", """quoted\t"""); Test_Cookie ("d", "s"); declare C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621"); Start : Util.Measures.Stamp; begin Set_Path (C, "/home"); Set_Domain (C, ".mydomain.example.com"); Set_Max_Age (C, 1000); Set_Http_Only (C, True); Set_Secure (C, True); Set_Comment (C, "some comment"); for I in 1 .. 1000 loop declare S : constant String := To_Http_Header (C); begin if S'Length < 10 then T.Assert (S'Length > 10, "Invalid cookie generation"); end if; end; end loop; Util.Measures.Report (S => Start, Title => "Generation of 1000 cookies"); end; end Test_To_Http_Header; -- ------------------------------ -- Test parsing of client cookie to build a list of Cookie objects -- ------------------------------ procedure Test_Parse_Http_Header (T : in out Test) is procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String); -- ------------------------------ -- Parse the header and check for the expected cookie count and verify -- the value of a specific cookie -- ------------------------------ procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String) is Start : Util.Measures.Stamp; C : Cookie_Array_Access := Get_Cookies (Header); Found : Boolean := False; begin Util.Measures.Report (S => Start, Title => "Parsing of cookie " & Name); T.Assert (C /= null, "Null value returned by Get_Cookies"); Assert_Equals (T, Count, C'Length, "Invalid count in result array"); for I in C'Range loop Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I))); if Name = Get_Name (C (I)) then Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name); Found := True; end if; end loop; T.Assert (Found, "Cookie " & Name & " not found"); Free (C); end Test_Parse; begin Test_Parse ("A=B", 1, "A", "B"); Test_Parse ("A=B=", 1, "A", "B="); Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5" & "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau" & "=sous_ouv_formulaire_chapeau_dei_config&nag=550&reg=14505; " & "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&" & "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5, "SES", "auth=0&cartridge_url=&return_url="); Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense=" & "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value", 6, "gpw_e24", "no%20value"); -- Parse a set of cookies from microsoft.com Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; " & "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; " & "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; " & "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; " & "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang=" & "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft." & "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 " & "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft" & ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits=" & "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795" & "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU" & "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7" & "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW" & "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5" & "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU" & "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68" & "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr" & "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6" & "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2" & "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u" & "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su" & "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; " & "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;" & ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY" & "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01", 15, "s_sq", "%5B%5BB%5D%5D"); Test_Parse ("A=B;", 1, "A", "B"); Test_Parse ("A=B; ", 1, "A", "B"); Test_Parse ("A=B; C&3", 1, "A", "B"); Test_Parse ("A=C; C<3=4", 1, "A", "C"); end Test_Parse_Http_Header; end Util.Http.Cookies.Tests;
----------------------------------------------------------------------- -- util-http-cookies-tests - Unit tests for Cookies -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with Util.Measures; with Ada.Strings.Fixed; with Ada.Unchecked_Deallocation; package body Util.Http.Cookies.Tests is use Ada.Strings.Fixed; use Util.Tests; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests"); procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access); package Caller is new Util.Test_Caller (Test, "Cookies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie", Test_Create_Cookie'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header", Test_To_Http_Header'Access); Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies", Test_Parse_Http_Header'Access); end Add_Tests; -- ------------------------------ -- Test creation of cookie -- ------------------------------ procedure Test_Create_Cookie (T : in out Test) is C : constant Cookie := Create ("cookie", "value"); begin T.Assert_Equals ("cookie", Get_Name (C), "Invalid name"); T.Assert_Equals ("value", Get_Value (C), "Invalid value"); T.Assert (not Is_Secure (C), "Invalid is_secure"); end Test_Create_Cookie; -- ------------------------------ -- Test conversion of cookie for HTTP header -- ------------------------------ procedure Test_To_Http_Header (T : in out Test) is procedure Test_Cookie (C : in Cookie); procedure Test_Cookie (Name : in String; Value : in String); procedure Test_Cookie (C : in Cookie) is S : constant String := To_Http_Header (C); begin Log.Info ("Cookie {0}: {1}", Get_Name (C), S); T.Assert (S'Length > 0, "Invalid cookie length for: " & S); T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S); end Test_Cookie; procedure Test_Cookie (Name : in String; Value : in String) is C : Cookie := Create (Name, Value); begin Test_Cookie (C); for I in 1 .. 24 loop Set_Max_Age (C, I * 3600 + I); Test_Cookie (C); end loop; Set_Secure (C, True); Test_Cookie (C); Set_Http_Only (C, True); Test_Cookie (C); Set_Domain (C, "world.com"); Test_Cookie (C); Set_Path (C, "/some-path"); Test_Cookie (C); end Test_Cookie; begin Test_Cookie ("a", "b"); Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1"); Test_Cookie ("p_41_zy", ""); Test_Cookie ("p_34", """quoted\t"""); Test_Cookie ("d", "s"); declare C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621"); Start : Util.Measures.Stamp; begin Set_Path (C, "/home"); Set_Domain (C, ".mydomain.example.com"); Set_Max_Age (C, 1000); Set_Http_Only (C, True); Set_Secure (C, True); Set_Comment (C, "some comment"); for I in 1 .. 1000 loop declare S : constant String := To_Http_Header (C); begin if S'Length < 10 then T.Assert (S'Length > 10, "Invalid cookie generation"); end if; end; end loop; Util.Measures.Report (S => Start, Title => "Generation of 1000 cookies"); end; end Test_To_Http_Header; -- ------------------------------ -- Test parsing of client cookie to build a list of Cookie objects -- ------------------------------ procedure Test_Parse_Http_Header (T : in out Test) is procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String); -- ------------------------------ -- Parse the header and check for the expected cookie count and verify -- the value of a specific cookie -- ------------------------------ procedure Test_Parse (Header : in String; Count : in Natural; Name : in String; Value : in String) is Start : Util.Measures.Stamp; C : Cookie_Array_Access := Get_Cookies (Header); Found : Boolean := False; begin Util.Measures.Report (S => Start, Title => "Parsing of cookie " & Name); T.Assert (C /= null, "Null value returned by Get_Cookies"); Assert_Equals (T, Count, C'Length, "Invalid count in result array"); for I in C'Range loop Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I))); if Name = Get_Name (C (I)) then Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name); Found := True; end if; end loop; T.Assert (Found, "Cookie " & Name & " not found"); Free (C); end Test_Parse; begin Test_Parse ("A=B", 1, "A", "B"); Test_Parse ("A=B=", 1, "A", "B="); Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5" & "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau" & "=sous_ouv_formulaire_chapeau_dei_config&nag=550&reg=14505; " & "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&" & "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5, "SES", "auth=0&cartridge_url=&return_url="); Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense=" & "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value", 6, "gpw_e24", "no%20value"); -- Parse a set of cookies from microsoft.com Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; " & "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; " & "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; " & "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; " & "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang=" & "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft." & "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 " & "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft" & ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits=" & "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795" & "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU" & "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7" & "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW" & "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5" & "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU" & "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68" & "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr" & "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6" & "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2" & "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u" & "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su" & "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; " & "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;" & ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY" & "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01", 15, "s_sq", "%5B%5BB%5D%5D"); Test_Parse ("A=B;", 1, "A", "B"); Test_Parse ("A=B; ", 1, "A", "B"); Test_Parse ("A=B; C&3", 1, "A", "B"); Test_Parse ("A=C; C<3=4", 2, "A", "C"); end Test_Parse_Http_Header; end Util.Http.Cookies.Tests;
Update the cookie unit test
Update the cookie unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ee85630bb7334138c3a986025e5893279765fed3
regtests/security-openid-tests.adb
regtests/security-openid-tests.adb
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Requests.Mockup; with ASF.Clients.Files; with Util.Test_Caller; with Util.Tests; with Ada.Text_IO; package body Security.Openid.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin ASF.Clients.Files.Register; ASF.Clients.Files.Set_File ( Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : ASF.Requests.Mockup.Request; M : Manager; Result : Authentication; begin M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Openid.Tests;
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Requests.Mockup; with ASF.Clients.Files; with Util.Test_Caller; with Ada.Text_IO; package body Security.Openid.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin ASF.Clients.Files.Register; ASF.Clients.Files.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : ASF.Requests.Mockup.Request; M : Manager; Result : Authentication; begin M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Openid.Tests;
Fix various compilation warnings
Fix various compilation warnings
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
8fdf977394fdcc18c2c3c378b18ef756516597c5
src/base/log/util-log-appenders-rolling_files.adb
src/base/log/util-log-appenders-rolling_files.adb
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2001 - 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.Finalization; with Ada.Directories; with Util.Properties.Basic; with Util.Log.Appenders.Formatter; package body Util.Log.Appenders.Rolling_Files is use Ada; use Ada.Finalization; package Bool_Prop renames Util.Properties.Basic.Boolean_Property; package Int_Prop renames Util.Properties.Basic.Integer_Property; -- ------------------------------ -- Finalize the referenced object. This is called before the object is freed. -- ------------------------------ overriding procedure Finalize (Object : in out File_Entity) is begin Text_IO.Close (File => Object.Output); end Finalize; protected body Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager) is function Get_Policy return Util.Files.Rolling.Policy_Type with Inline; function Get_Strategy return Util.Files.Rolling.Strategy_Type with Inline; File : constant String := Properties.Get (Base & ".fileName", Name & ".log"); Pat : constant String := Properties.Get (Base & ".filePattern", Base & "-%i.log"); function Get_Policy return Util.Files.Rolling.Policy_Type is Str : constant String := Properties.Get (Base & ".policy", "time"); Inter : constant Integer := Int_Prop.Get (Properties, Base & ".policyInterval", 1); Size : constant String := Properties.Get (Base & ".minSize", "1000000"); begin if Str = "none" then return (Kind => Util.Files.Rolling.No_Policy); elsif Str = "time" then return (Kind => Util.Files.Rolling.Time_Policy, Interval => Inter); else return (Kind => Util.Files.Rolling.Size_Policy, Size => Ada.Directories.File_Size'Value (Size)); end if; exception when others => return (Kind => Util.Files.Rolling.No_Policy); end Get_Policy; function Get_Strategy return Util.Files.Rolling.Strategy_Type is Str : constant String := Properties.Get (Base & ".strategy", "ascending"); Min : constant Integer := Int_Prop.Get (Properties, Base & ".policyMin", 0); Max : constant Integer := Int_Prop.Get (Properties, Base & ".policyMax", 0); begin if Str = "direct" then return (Kind => Util.Files.Rolling.Direct_Strategy, Max_Files => Max); elsif Str = "descending" then return (Kind => Util.Files.Rolling.Descending_Strategy, Min_Index => Min, Max_Index => Max); else return (Kind => Util.Files.Rolling.Ascending_Strategy, Min_Index => Min, Max_Index => Max); end if; end Get_Strategy; begin Append := Bool_Prop.Get (Properties, Base & ".append", True); Manager.Initialize (Path => File, Pattern => Pat, Policy => Get_Policy, Strategy => Get_Strategy); end Initialize; procedure Openlog (File : out File_Refs.Ref) is begin if not Manager.Is_Rollover_Necessary then File := Current; return; end if; Closelog; Current := File_Refs.Create; Manager.Rollover; declare Path : constant String := Manager.Get_Current_Path; Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Path (Dir); end if; if not Ada.Directories.Exists (Path) then Text_IO.Create (File => Current.Value.Output, Name => Path); else Text_IO.Open (File => Current.Value.Output, Name => Path, Mode => (if Append then Text_IO.Append_File else Text_IO.Out_File)); end if; end; end Openlog; procedure Flush (File : out File_Refs.Ref) is begin if not Current.Is_Null then File := Current; end if; end Flush; procedure Closelog is Empty : File_Refs.Ref; begin -- Close the current log by releasing its reference counter. Current := Empty; end Closelog; end Rolling_File; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String) is begin if Self.Level >= Level then declare File : File_Refs.Ref; procedure Write_File (Data : in String) with Inline_Always; procedure Write_File (Data : in String) is begin Text_IO.Put (File.Value.Output, Data); end Write_File; procedure Write is new Formatter (Write_File); begin Self.File.Openlog (File); if not File.Is_Null then Write (Self, Message, Date, Level, Logger); Text_IO.New_Line (File.Value.Output); if Self.Immediate_Flush then Text_IO.Flush (File.Value.Output); end if; end if; end; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is File : File_Refs.Ref; begin Self.File.Flush (File); if not File.Is_Null then Text_IO.Flush (File.Value.Output); end if; end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.File.Closelog; end Finalize; -- ------------------------------ -- Create a file appender and configure it according to the properties -- ------------------------------ function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is Base : constant String := "appender." & Name; Result : constant File_Appender_Access := new File_Appender '(Limited_Controlled with Length => Name'Length, Name => Name, others => <>); begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Immediate_Flush := Bool_Prop.Get (Properties, Base & ".immediateFlush", True); Result.File.Initialize (Name, Base, Properties); return Result.all'Access; end Create; end Util.Log.Appenders.Rolling_Files;
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2001 - 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.Finalization; with Ada.Directories; with Util.Properties.Basic; with Util.Log.Appenders.Formatter; package body Util.Log.Appenders.Rolling_Files is use Ada; use Ada.Finalization; package Bool_Prop renames Util.Properties.Basic.Boolean_Property; package Int_Prop renames Util.Properties.Basic.Integer_Property; -- ------------------------------ -- Finalize the referenced object. This is called before the object is freed. -- ------------------------------ overriding procedure Finalize (Object : in out File_Entity) is begin Text_IO.Close (File => Object.Output); end Finalize; protected body Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager) is function Get_Policy return Util.Files.Rolling.Policy_Type with Inline; function Get_Strategy return Util.Files.Rolling.Strategy_Type with Inline; File : constant String := Properties.Get (Base & ".fileName", Name & ".log"); Pat : constant String := Properties.Get (Base & ".filePattern", Base & "-%i.log"); function Get_Policy return Util.Files.Rolling.Policy_Type is Str : constant String := Properties.Get (Base & ".policy", "time"); Inter : constant Integer := Int_Prop.Get (Properties, Base & ".policyInterval", 1); Size : constant String := Properties.Get (Base & ".minSize", "1000000"); begin if Str = "none" then return (Kind => Util.Files.Rolling.No_Policy); elsif Str = "time" then return (Kind => Util.Files.Rolling.Time_Policy, Interval => Inter); else return (Kind => Util.Files.Rolling.Size_Policy, Size => Ada.Directories.File_Size'Value (Size)); end if; exception when others => return (Kind => Util.Files.Rolling.No_Policy); end Get_Policy; function Get_Strategy return Util.Files.Rolling.Strategy_Type is Str : constant String := Properties.Get (Base & ".strategy", "ascending"); Min : constant Integer := Int_Prop.Get (Properties, Base & ".policyMin", 0); Max : constant Integer := Int_Prop.Get (Properties, Base & ".policyMax", 0); begin if Str = "direct" then return (Kind => Util.Files.Rolling.Direct_Strategy, Max_Files => Max); elsif Str = "descending" then return (Kind => Util.Files.Rolling.Descending_Strategy, Min_Index => Min, Max_Index => Max); else return (Kind => Util.Files.Rolling.Ascending_Strategy, Min_Index => Min, Max_Index => Max); end if; end Get_Strategy; begin Append := Bool_Prop.Get (Properties, Base & ".append", True); Manager.Initialize (Path => File, Pattern => Pat, Policy => Get_Policy, Strategy => Get_Strategy); end Initialize; procedure Openlog (File : out File_Refs.Ref) is begin if not Current.Is_Null then if not Manager.Is_Rollover_Necessary then File := Current; return; end if; Closelog; Manager.Rollover; end if; Current := File_Refs.Create; declare Path : constant String := Manager.Get_Current_Path; Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Path (Dir); end if; if not Ada.Directories.Exists (Path) then Text_IO.Create (File => Current.Value.Output, Name => Path); else Text_IO.Open (File => Current.Value.Output, Name => Path, Mode => (if Append then Text_IO.Append_File else Text_IO.Out_File)); end if; end; end Openlog; procedure Flush (File : out File_Refs.Ref) is begin if not Current.Is_Null then File := Current; end if; end Flush; procedure Closelog is Empty : File_Refs.Ref; begin -- Close the current log by releasing its reference counter. Current := Empty; end Closelog; end Rolling_File; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String) is begin if Self.Level >= Level then declare File : File_Refs.Ref; procedure Write_File (Data : in String) with Inline_Always; procedure Write_File (Data : in String) is begin Text_IO.Put (File.Value.Output, Data); end Write_File; procedure Write is new Formatter (Write_File); begin Self.File.Openlog (File); if not File.Is_Null then Write (Self, Message, Date, Level, Logger); Text_IO.New_Line (File.Value.Output); if Self.Immediate_Flush then Text_IO.Flush (File.Value.Output); end if; end if; end; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is File : File_Refs.Ref; begin Self.File.Flush (File); if not File.Is_Null then Text_IO.Flush (File.Value.Output); end if; end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.File.Closelog; end Finalize; -- ------------------------------ -- Create a file appender and configure it according to the properties -- ------------------------------ function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is Base : constant String := "appender." & Name; Result : constant File_Appender_Access := new File_Appender '(Limited_Controlled with Length => Name'Length, Name => Name, others => <>); begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Immediate_Flush := Bool_Prop.Get (Properties, Base & ".immediateFlush", True); Result.File.Initialize (Name, Base, Properties); return Result.all'Access; end Create; end Util.Log.Appenders.Rolling_Files;
Fix opening the first log
Fix opening the first log
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6a7cda648628c479f8e53163fed05055b54867fc
src/gen-artifacts-yaml.ads
src/gen-artifacts-yaml.ads
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Yaml database model files -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Packages; package Gen.Artifacts.Yaml is -- ------------------------------ -- Yaml artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- 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; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class; Is_Predefined : in Boolean := False); private type Artifact is new Gen.Artifacts.Artifact with null record; end Gen.Artifacts.Yaml;
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Yaml database model files -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Packages; package Gen.Artifacts.Yaml is -- ------------------------------ -- Yaml artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- 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; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with null record; end Gen.Artifacts.Yaml;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5e227e34b47758282c7c0c8d530cbe3416a98183
src/base/os-macos64/util-systems-types.ads
src/base/os-macos64/util-systems-types.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Types is subtype dev_t is Interfaces.C.unsigned; subtype ino_t is Long_Long_Integer; subtype off_t is Long_Long_Integer; subtype blksize_t is Interfaces.C.int; subtype blkcnt_t is Long_Long_Integer; subtype uid_t is Interfaces.C.unsigned; subtype gid_t is Interfaces.C.unsigned; subtype nlink_t is Interfaces.C.unsigned_short; subtype mode_t is Interfaces.C.unsigned_short; S_IFMT : constant mode_t := 8#00170000#; S_IFDIR : constant mode_t := 8#00040000#; S_IFCHR : constant mode_t := 8#00020000#; S_IFBLK : constant mode_t := 8#00060000#; S_IFREG : constant mode_t := 8#00100000#; S_IFIFO : constant mode_t := 8#00010000#; S_IFLNK : constant mode_t := 8#00120000#; S_IFSOCK : constant mode_t := 8#00140000#; S_ISUID : constant mode_t := 8#00004000#; S_ISGID : constant mode_t := 8#00002000#; S_IREAD : constant mode_t := 8#00000400#; S_IWRITE : constant mode_t := 8#00000200#; S_IEXEC : constant mode_t := 8#00000100#; type File_Type is new Interfaces.C.int; subtype Time_Type is Long_Long_Integer; type Timespec is record tv_sec : Time_Type; tv_nsec : Long_Long_Integer; end record; pragma Convention (C_Pass_By_Copy, Timespec); type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END); for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2); -- Size = 144 -- st_dev = 4 -- st_mode = 2 -- st_uid = 4 -- st_atim = 8 -- st_nlink@ 6 -- st_rdev@ 24 -- st_size@ 96 STAT_NAME : constant String := "_stat64"; FSTAT_NAME : constant String := "_fstat64"; type Stat_Type is record st_dev : dev_t; st_mode : mode_t; st_nlink : nlink_t; st_ino : ino_t; st_uid : uid_t; st_gid : gid_t; st_rdev : dev_t; st_atim : Timespec; st_mtim : Timespec; st_ctim : Timespec; st_birthtim : Timespec; st_size : off_t; st_blocks : blkcnt_t; st_blksize : blksize_t; st_flags : Interfaces.C.unsigned; st_gen : Interfaces.C.unsigned; st_lspare : Interfaces.C.unsigned; st_qspare1 : Interfaces.C.unsigned; st_qspare2 : Interfaces.C.unsigned; st_qspare3 : Interfaces.C.unsigned; st_qspare4 : Interfaces.C.unsigned; end record; pragma Convention (C_Pass_By_Copy, Stat_Type); end Util.Systems.Types;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Types is subtype dev_t is Interfaces.C.unsigned; subtype ino_t is Long_Long_Integer; subtype off_t is Long_Long_Integer; subtype blksize_t is Interfaces.C.int; subtype blkcnt_t is Long_Long_Integer; subtype uid_t is Interfaces.C.unsigned; subtype gid_t is Interfaces.C.unsigned; subtype nlink_t is Interfaces.C.unsigned_short; subtype mode_t is Interfaces.C.unsigned_short; S_IFMT : constant mode_t := 8#00170000#; S_IFDIR : constant mode_t := 8#00040000#; S_IFCHR : constant mode_t := 8#00020000#; S_IFBLK : constant mode_t := 8#00060000#; S_IFREG : constant mode_t := 8#00100000#; S_IFIFO : constant mode_t := 8#00010000#; S_IFLNK : constant mode_t := 8#00120000#; S_IFSOCK : constant mode_t := 8#00140000#; S_ISUID : constant mode_t := 8#00004000#; S_ISGID : constant mode_t := 8#00002000#; S_IREAD : constant mode_t := 8#00000400#; S_IWRITE : constant mode_t := 8#00000200#; S_IEXEC : constant mode_t := 8#00000100#; type File_Type is new Interfaces.C.int; subtype Time_Type is Long_Long_Integer; type Timespec is record tv_sec : Time_Type; tv_nsec : Long_Long_Integer; end record; pragma Convention (C_Pass_By_Copy, Timespec); type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END); for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2); -- Size = 144 -- st_dev = 4 -- st_mode = 2 -- st_uid = 4 -- st_atim = 8 -- st_nlink@ 6 -- st_rdev@ 24 -- st_size@ 96 STAT_NAME : constant String := "_stat64"; LSTAT_NAME : constant String := "_lstat64"; FSTAT_NAME : constant String := "_fstat64"; type Stat_Type is record st_dev : dev_t; st_mode : mode_t; st_nlink : nlink_t; st_ino : ino_t; st_uid : uid_t; st_gid : gid_t; st_rdev : dev_t; st_atim : Timespec; st_mtim : Timespec; st_ctim : Timespec; st_birthtim : Timespec; st_size : off_t; st_blocks : blkcnt_t; st_blksize : blksize_t; st_flags : Interfaces.C.unsigned; st_gen : Interfaces.C.unsigned; st_lspare : Interfaces.C.unsigned; st_qspare1 : Interfaces.C.unsigned; st_qspare2 : Interfaces.C.unsigned; st_qspare3 : Interfaces.C.unsigned; st_qspare4 : Interfaces.C.unsigned; end record; pragma Convention (C_Pass_By_Copy, Stat_Type); end Util.Systems.Types;
Add LSTAT_NAME for MacOS
Add LSTAT_NAME for MacOS
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
93364ab9df1fa1db475577736ea338c10d7a26b1
src/asf-navigations-render.adb
src/asf-navigations-render.adb
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- Copyright (C) 2010, 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with ASF.Components.Root; package body ASF.Navigations.Render is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations.Render"); -- ------------------------------ -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. -- ------------------------------ overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : Components.Root.UIViewRoot; begin Log.Debug ("Navigate to view {0}", Controller.View_Name); if Controller.Status /= 0 then Context.Get_Response.Set_Status (Controller.Status); end if; Controller.View_Handler.Create_View (Controller.View_Name, Context, View); Context.Set_View_Root (View); exception when E : others => Log.Error ("Error when navigating to view {0}: {1}: {2}", Controller.View_Name, Exception_Name (E), Exception_Message (E)); raise; end Navigate; -- ------------------------------ -- Create a navigation case to render a view. -- ------------------------------ function Create_Render_Navigator (To_View : in String; Status : in Natural) return Navigation_Access is Result : constant Render_Navigator_Access := new Render_Navigator '(Len => To_View'Length, Status => Status, View_Name => To_View, others => <>); begin return Result.all'Access; end Create_Render_Navigator; end ASF.Navigations.Render;
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- Copyright (C) 2010, 2011, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with ASF.Components.Root; package body ASF.Navigations.Render is use Ada.Exceptions; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations.Render"); -- ------------------------------ -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. -- ------------------------------ overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : Components.Root.UIViewRoot; begin Log.Debug ("Navigate to view {0}", Controller.View_Name); if Controller.Status /= 0 then Context.Get_Response.Set_Status (Controller.Status); end if; Controller.View_Handler.Create_View (Controller.View_Name, Context, View); Context.Set_View_Root (View); exception when E : others => Log.Error ("Error when navigating to view {0}: {1}: {2}", Controller.View_Name, Exception_Name (E), Exception_Message (E)); raise; end Navigate; -- ------------------------------ -- Create a navigation case to render a view. -- ------------------------------ function Create_Render_Navigator (To_View : in String; Status : in Natural) return Navigation_Access is Result : constant Render_Navigator_Access := new Render_Navigator '(Len => To_View'Length, Status => Status, View_Name => To_View, others => <>); begin return Result.all'Access; end Create_Render_Navigator; end ASF.Navigations.Render;
Remove unused use clauses
Remove unused use clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8e59f31f6d7df506f305fedd9237862b5c878066
regtests/wiki-writers-tests.adb
regtests/wiki-writers-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Utils; package body Wiki.Writers.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, T.Format); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)), Wiki.Parsers.SYNTAX_HTML); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Writers.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Ada.Characters.Conversions; with Util.Files; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Filters.Html; with Wiki.Writers.Builders; with Wiki.Utils; package body Wiki.Writers.Tests is use Ada.Strings.Unbounded; use type Wiki.Parsers.Wiki_Syntax_Type; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Result_File : constant String := To_String (T.Result); Content : Unbounded_String; begin Util.Files.Read_File (Path => To_String (T.File), Into => Content, Max_Size => 10000); declare Time : Util.Measures.Stamp; begin if T.Source = Wiki.Parsers.SYNTAX_HTML then declare Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access, T.Format); Html_Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Html_Filter'Unchecked_Access, To_Wide (To_String (Content)), Wiki.Parsers.SYNTAX_HTML); Content := To_Unbounded_String (Writer.To_String); end; elsif T.Is_Html then Content := To_Unbounded_String (Utils.To_Html (To_Wide (To_String (Content)), T.Format)); else Content := To_Unbounded_String (Utils.To_Text (To_Wide (To_String (Content)), T.Format)); end if; Util.Measures.Report (Time, "Render " & To_String (T.Name)); end; Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.Parsers.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Parsers.Wiki_Syntax_Type; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Parsers.Wiki_Syntax_Type; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.Parsers.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.Parsers.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.Parsers.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.Parsers.SYNTAX_MEDIA_WIKI; else Format := Wiki.Parsers.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Parsers.Wiki_Syntax_Type'Range loop case Syntax is when Wiki.Parsers.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.Parsers.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.Parsers.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Writers.Tests;
Update the import test for the Dotclear syntax import
Update the import test for the Dotclear syntax import
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
63d3cceebc75a561254dea5eba1ec36eae5494e9
src/http/util-http-clients.adb
src/http/util-http-clients.adb
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Http.Clients is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; 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. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; 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 Response; Name : in String; Value : in String) is begin if Reply.Delegate = null then null; end if; Reply.Delegate.Set_Header (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 (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin return Request.Delegate.Contains_Header (Name); 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 Client; Name : in String) return String is begin return Request.Delegate.Get_Header (Name); end Get_Header; -- ------------------------------ -- Sets a 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 (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Http.Clients is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; 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. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; 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 Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (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 (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; 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 Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a 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 (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
Check that the delegate instance is not null
Check that the delegate instance is not null
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
c3898b20e7a0a7a977c55ac31ddc66295a046bc6
matp/src/events/mat-events-tools.adb
matp/src/events/mat-events-tools.adb
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Tools is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; function "<" (Left, Right : in Frame_Key_Type) return Boolean is begin if Left.Addr < Right.Addr then return True; elsif Left.Addr > Right.Addr then return False; else return Left.Level < Right.Level; end if; end "<"; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; end MAT.Events.Tools;
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Tools is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; function "<" (Left, Right : in Frame_Key_Type) return Boolean is begin if Left.Addr < Right.Addr then return True; elsif Left.Addr > Right.Addr then return False; else return Left.Level < Right.Level; end if; end "<"; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. -- ------------------------------ procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector) is function "<" (Left, Right : in Frame_Info_Type) return Boolean; function "<" (Left, Right : in Frame_Info_Type) return Boolean is begin if Left.Key.Level < Right.Key.Level then return True; else return False; end if; end "<"; package Sort_Frame_Info is new Frame_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Frame_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item.Key := Frame_Event_Info_Maps.Key (Iter); Item.Info := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Frame_Info.Sort (List); end Build_Frame_Info; end MAT.Events.Tools;
Implement Build_Frame_Info to collect the frame data and sort them
Implement Build_Frame_Info to collect the frame data and sort them
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
35439332f795664c9919ada4cc69dac9627ff046
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record Count : Natural := 0; Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Get the server port. function Get_Port (Controller : in Configuration) return Integer; -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Integer := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record Count : Natural := 0; Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Set the server hostname. procedure Set_Server (Controller : in out Configuration; Server : in String); -- Get the server hostname. function Get_Server (Controller : in Configuration) return String; -- Set the server port. procedure Set_Port (Controller : in out Configuration; Port : in Natural); -- Get the server port. function Get_Port (Controller : in Configuration) return Natural; -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Natural := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers.Connections;
Declare the Set_Port procedure and change the port type to a natural
Declare the Set_Port procedure and change the port type to a natural
Ada
apache-2.0
stcarrez/ada-ado
d7446a76f996311e1a9cebe4d93cca322c7f6c15
regtests/security-auth-tests.adb
regtests/security-auth-tests.adb
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- 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 Ada.Strings.Unbounded; with Util.Http.Mockups; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); -- M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); -- M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
Fix compilation warning: unused with clause
Fix compilation warning: unused with clause
Ada
apache-2.0
stcarrez/ada-security
3bc7e04a7c873d993f6731c4730a0c33ea87f911
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); -- Test Decode Quoted-Printable encoding. procedure Test_Decode_Quoted_Printable (T : in out Test); end Util.Encoders.Tests;
Declare the Test_Decode_Quoted_Printable procedure
Declare the Test_Decode_Quoted_Printable procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0345b8db006026d59eba6295cde43ecf7c00bce5
src/util-commands-consoles.ads
src/util-commands-consoles.ads
----------------------------------------------------------------------- -- util-commands-consoles -- Console interface -- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; generic type Field_Type is (<>); type Notice_Type is (<>); package Util.Commands.Consoles is type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; -- Reset the field count. procedure Clear_Fields (Console : in out Console_Type); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Size_Array'Length) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end Util.Commands.Consoles;
----------------------------------------------------------------------- -- util-commands-consoles -- Console interface -- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; generic type Field_Type is (<>); type Notice_Type is (<>); package Util.Commands.Consoles is type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; -- Reset the field count. procedure Clear_Fields (Console : in out Console_Type); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Size_Array'Length) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 0); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end Util.Commands.Consoles;
Initialize the sizes to 0 by default
Initialize the sizes to 0 by default
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ccd5b81a670d064101fd52c53d8260fbe1e6bb5e
awa/src/awa-commands-drivers.adb
awa/src/awa-commands-drivers.adb
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); --if Context.Debug or Context.Verbose or Context.Dump then -- AKT.Configure_Logs (Debug => Context.Debug, -- Dump => Context.Dump, -- Verbose => Context.Verbose); --end if; if Context.Config_File'Length > 0 then Context.Load_Configuration (Context.Config_File.all); else Context.Load_Configuration (Driver_Name & ".properties"); end if; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); if Context.Config_File'Length > 0 then Context.Load_Configuration (Context.Config_File.all); else Context.Load_Configuration (Driver_Name & ".properties"); end if; if Context.Debug or Context.Verbose or Context.Dump then Configure_Logs (Root => Context.File_Config.Get ("log4j.rootCategory", ""), Debug => Context.Debug, Dump => Context.Dump, Verbose => Context.Verbose); end if; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
Configure the logs with Configure_Logs
Configure the logs with Configure_Logs
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
60e6989b2afc484cb8165a288a85b0528cdecffd
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Get the number of roles set in the map. -- ------------------------------ function Get_Count (Map : in Role_Map) return Natural is Count : Natural := 0; begin for R of Map loop if R then Count := Count + 1; end if; end loop; return Count; end Get_Count; -- ------------------------------ -- Get the list of role names that are defined by the role map. -- ------------------------------ function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array is Result : Role_Name_Array (1 .. Get_Count (Map)); Pos : Positive := 1; begin for Role in Map'Range loop if Map (Role) then Result (Pos) := Manager.Names (Role); Pos := Pos + 1; end if; end loop; return Result; end Get_Role_Names; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Util.Strings.Builders; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Get the number of roles set in the map. -- ------------------------------ function Get_Count (Map : in Role_Map) return Natural is Count : Natural := 0; begin for R of Map loop if R then Count := Count + 1; end if; end loop; return Count; end Get_Count; -- ------------------------------ -- Return the list of role names separated by ','. -- ------------------------------ function To_String (List : in Role_Name_Array) return String is use type Ada.Strings.Unbounded.String_Access; Buf : Util.Strings.Builders.Builder (Len => 256); Need_Colon : Boolean := False; begin for Name of List loop if Name /= null then if Need_Colon then Util.Strings.Builders.Append (Buf, ","); end if; Util.Strings.Builders.Append (Buf, Name.all); Need_Colon := True; end if; end loop; return Util.Strings.Builders.To_Array (Buf); end To_String; -- ------------------------------ -- Get the list of role names that are defined by the role map. -- ------------------------------ function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array is Result : Role_Name_Array (1 .. Get_Count (Map)); Pos : Positive := 1; begin for Role in Map'Range loop if Map (Role) then Result (Pos) := Manager.Names (Role); Pos := Pos + 1; end if; end loop; return Result; end Get_Role_Names; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Implement the To_String function
Implement the To_String function
Ada
apache-2.0
stcarrez/ada-security
e48d63f839ceae83514f74f8e8c4a6543ff9ddce
src/util-properties-bundles.adb
src/util-properties-bundles.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Bundle.Impl.Count := Bundle.Impl.Count + 1; Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl = null then Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; end if; Util.Concurrent.Counters.Increment (Object.Impl.Count); end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Util.Concurrent.Counters.Increment (Bundle.Impl.Count); Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
Update to use the concurrent counters
Update to use the concurrent counters
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a6839df17bd6c1f66625ea371d37acbe720d37c8
src/util-serialize-contexts.adb
src/util-serialize-contexts.adb
----------------------------------------------------------------------- -- util-serialize-contexts -- Contexts for serialization framework -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Concurrent.Locks; package body Util.Serialize.Contexts is procedure Free is new Ada.Unchecked_Deallocation (Data'Class, Data_Access); -- ------------------------------ -- Context data key -- ------------------------------ Lock : Util.Concurrent.Locks.RW_Lock; Next_Key : Data_Key := 1; -- ------------------------------ -- Allocate a unique data key for a mapper. -- ------------------------------ procedure Allocate (Key : out Data_Key) is begin Lock.Write; Key := Next_Key; Next_Key := Next_Key + 1; Lock.Release_Write; end Allocate; function Hash (Key : in Data_Key) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Reader context -- ------------------------------ -- ------------------------------ -- Get the data object associated with the given key. -- Raises No_Data exception if there is no data object. -- ------------------------------ function Get_Data (Ctx : in Context; Key : in Data_Key) return Data_Access is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then return Data_Map.Element (Pos); else raise No_Data; end if; end Get_Data; -- ------------------------------ -- Set the data object associated with the given key. -- ------------------------------ procedure Set_Data (Ctx : in out Context; Key : in Data_Key; Content : in Data_Access) is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then declare Old : Data_Access := Data_Map.Element (Pos); begin if Old = Content then return; end if; Free (Old); end; Ctx.Data.Replace_Element (Position => Pos, New_Item => Content); else Ctx.Data.Insert (Key => Key, New_Item => Content); end if; end Set_Data; -- ------------------------------ -- Free the context data. -- ------------------------------ overriding procedure Finalize (Ctx : in out Context) is Pos : Data_Map.Cursor; Content : Data_Access; begin loop Pos := Ctx.Data.First; exit when not Data_Map.Has_Element (Pos); Content := Data_Map.Element (Pos); Free (Content); Ctx.Data.Delete (Pos); end loop; end Finalize; end Util.Serialize.Contexts;
----------------------------------------------------------------------- -- util-serialize-contexts -- Contexts for serialization framework -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Concurrent.Counters; package body Util.Serialize.Contexts is procedure Free is new Ada.Unchecked_Deallocation (Data'Class, Data_Access); -- ------------------------------ -- Context data key -- ------------------------------ Next_Key : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; -- ------------------------------ -- Allocate a unique data key for a mapper. -- ------------------------------ procedure Allocate (Key : out Data_Key) is Val : Integer; begin Util.Concurrent.Counters.Increment (Next_Key, Val); Key := Data_Key (Val); end Allocate; function Hash (Key : in Data_Key) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Reader context -- ------------------------------ -- ------------------------------ -- Get the data object associated with the given key. -- Raises No_Data exception if there is no data object. -- ------------------------------ function Get_Data (Ctx : in Context; Key : in Data_Key) return Data_Access is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then return Data_Map.Element (Pos); else raise No_Data; end if; end Get_Data; -- ------------------------------ -- Set the data object associated with the given key. -- ------------------------------ procedure Set_Data (Ctx : in out Context; Key : in Data_Key; Content : in Data_Access) is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then declare Old : Data_Access := Data_Map.Element (Pos); begin if Old = Content then return; end if; Free (Old); end; Ctx.Data.Replace_Element (Position => Pos, New_Item => Content); else Ctx.Data.Insert (Key => Key, New_Item => Content); end if; end Set_Data; -- ------------------------------ -- Free the context data. -- ------------------------------ overriding procedure Finalize (Ctx : in out Context) is Pos : Data_Map.Cursor; Content : Data_Access; begin loop Pos := Ctx.Data.First; exit when not Data_Map.Has_Element (Pos); Content := Data_Map.Element (Pos); Free (Content); Ctx.Data.Delete (Pos); end loop; end Finalize; end Util.Serialize.Contexts;
Use the atomic increment and get counter operation instead of a RW lock
Use the atomic increment and get counter operation instead of a RW lock
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
8736f6f8055d27a8ea58526fa518a83a077e0c4b
tools/druss-commands-bboxes.adb
tools/druss-commands-bboxes.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Properties; with Druss.Gateways; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Put (To_String (Gateway.Ip)); Set_Col (30); Put (Gateway.Wan.Get ("wan.internet.state", "?")); Set_Col (38); Put (Gateway.Wan.Get ("wan.ip.address", "?")); Set_Col (60); Put (Gateway.Device.Get ("device.numberofboots", "-")); Set_Col (68); Put (Gateway.Device.Get ("device.uptime", "-")); New_Line; end Box_Status; -- Execute the command with the arguments. The command name is passed with the command -- arguments. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin Druss.Gateways.Iterate (Context.Gateways, Box_Status'Access); end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Operations to control the bbox"); Put_Line ("Usage: druss bbox list"); Put_Line (" druss bbox add IP"); Put_Line (" druss bbox del IP"); end Help; end Druss.Commands.Bboxes;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- 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.Text_IO; with Ada.Streams; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; procedure Discover (Command : in Command_Type) is IPs : Util.Strings.Sets.Set; Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Process (URI : in String) is Pos2 : Natural; begin -- http:// Pos2 := Util.Strings.Index (URI, ':', 7); if Pos2 > 0 and then not IPs.Contains (URI (URI'First + 7 .. Pos2 - 1)) then Log.Info ("Detected an IGD device at {0}", URI (URI'First + 7 .. Pos2 - 1)); IPs.Include (URI (URI'First + 7 .. Pos2 - 1)); end if; Log.Warn ("Found: {0}", URI); end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; for IP of IPs loop Discover (IP); end loop; end Discover; -- Execute the command with the arguments. The command name is passed with the command -- arguments. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover; end if; end Execute; -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" The Bbox API operation are called and the raw JSON result is printed."); Put_Line (" When several operations are called, a JSON array is formed to insert"); Put_Line (" their result in the final JSON content so that it is valid."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox Get information about the Bbox"); Put_Line (" bbox del IP Get the list of hosts detected by the Bbox"); end Help; end Druss.Commands.Bboxes;
Implement the Discover procedure by using SSDP to discover the IGD devices and doing a Bbox API call
Implement the Discover procedure by using SSDP to discover the IGD devices and doing a Bbox API call
Ada
apache-2.0
stcarrez/bbox-ada-api
80fdb15df2022637241e7ccdb9717527a30c7291
regtests/asf-servlets-tests.adb
regtests/asf-servlets-tests.adb
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Routes.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Filters.Dump; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. -- ------------------------------ procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String) is use type ASF.Routes.Route_Type_Access; Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Context.Get_Route /= null, "No mapping found for " & URI); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path"); Assert_Equals (T, Path_Info, Req.Get_Path_Info, "The request path info is invalid"); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end Check_Request; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/home/test.jsf", "/home/test.jsf", ""); end Test_Request_Dispatcher; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Servlet_Path (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html"); end Test_Servlet_Path; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Filter_Mapping (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; F1 : aliased ASF.Filters.Dump.Dump_Filter; F2 : aliased ASF.Filters.Dump.Dump_Filter; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Servlet ("Json", S2'Unchecked_Access); Ctx.Add_Filter ("Dump", F1'Unchecked_Access); Ctx.Add_Filter ("Dump2", F2'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.json", Name => "Json"); Ctx.Add_Filter_Mapping (Pattern => "/dump/file.html", Name => "Dump"); Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump"); Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump2"); Ctx.Start; T.Check_Mapping (Ctx, "test.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "file.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "/dump/test.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "/dump/file.html", S1'Unchecked_Access, 1); T.Check_Mapping (Ctx, "/dump/result/test.html", S1'Unchecked_Access, 2); T.Check_Mapping (Ctx, "test.json", S2'Unchecked_Access); end Test_Filter_Mapping; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0) is use type ASF.Routes.Route_Type_Access; use type ASF.Filters.Filter_List_Access; Disp : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (URI); Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route; Servlet_Route : ASF.Routes.Servlets.Servlet_Route_Type_Access; begin if Server = null then T.Assert (Route = null, "No mapping returned for URI: " & URI); else T.Assert (Route /= null, "A mapping is returned for URI: " & URI); T.Assert (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class, "The route is not a Servlet route"); Servlet_Route := ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all)'Access; T.Assert (Servlet_Route.Servlet = Server, "Invalid mapping returned for URI: " & URI); if Filter = 0 then T.Assert (Disp.Filters = null, "Filters are configured for URI: " & URI); else T.Assert (Disp.Filters /= null, "No filter on the route URI: " & URI); Util.Tests.Assert_Equals (T, Filter, Disp.Filters'Length, "Invalid mapping returned for URI: " & URI); end if; end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); -- Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); -- declare -- St : Util.Measures.Stamp; -- begin -- for I in 1 .. 1000 loop -- Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); -- end loop; -- Util.Measures.Report (St, "Find 1000 mapping (extension)"); -- end; -- T.Assert (Map /= null, "No mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); -- declare -- St : Util.Measures.Stamp; -- begin -- for I in 1 .. 1000 loop -- Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); -- end loop; -- Util.Measures.Report (St, "Find 1000 mapping (path)"); -- end; -- -- T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); -- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path", Test_Servlet_Path'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Filter", Test_Filter_Mapping'Access); end Add_Tests; end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Routes.Servlets; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Filters.Dump; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. -- ------------------------------ procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String) is use type ASF.Routes.Route_Type_Access; Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Context.Get_Route /= null, "No mapping found for " & URI); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path"); Assert_Equals (T, Path_Info, Req.Get_Path_Info, "The request path info is invalid"); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end Check_Request; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/home/test.jsf", "/home/test.jsf", ""); end Test_Request_Dispatcher; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Servlet_Path (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html"); Check_Request (T, Ctx, "/root/home/test.jsf", "/root/home/test.jsf", ""); Check_Request (T, Ctx, "/test.jsf", "/test.jsf", ""); end Test_Servlet_Path; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Filter_Mapping (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; F1 : aliased ASF.Filters.Dump.Dump_Filter; F2 : aliased ASF.Filters.Dump.Dump_Filter; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Servlet ("Json", S2'Unchecked_Access); Ctx.Add_Filter ("Dump", F1'Unchecked_Access); Ctx.Add_Filter ("Dump2", F2'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.json", Name => "Json"); Ctx.Add_Filter_Mapping (Pattern => "/dump/file.html", Name => "Dump"); Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump"); Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump2"); Ctx.Start; T.Check_Mapping (Ctx, "test.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "file.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "/dump/test.html", S1'Unchecked_Access); T.Check_Mapping (Ctx, "/dump/file.html", S1'Unchecked_Access, 1); T.Check_Mapping (Ctx, "/dump/result/test.html", S1'Unchecked_Access, 2); T.Check_Mapping (Ctx, "test.json", S2'Unchecked_Access); end Test_Filter_Mapping; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0) is use type ASF.Routes.Route_Type_Access; use type ASF.Filters.Filter_List_Access; Disp : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (URI); Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route; Servlet_Route : ASF.Routes.Servlets.Servlet_Route_Type_Access; begin if Server = null then T.Assert (Route = null, "No mapping returned for URI: " & URI); else T.Assert (Route /= null, "A mapping is returned for URI: " & URI); T.Assert (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class, "The route is not a Servlet route"); Servlet_Route := ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all)'Access; T.Assert (Servlet_Route.Servlet = Server, "Invalid mapping returned for URI: " & URI); if Filter = 0 then T.Assert (Disp.Filters = null, "Filters are configured for URI: " & URI); else T.Assert (Disp.Filters /= null, "No filter on the route URI: " & URI); Util.Tests.Assert_Equals (T, Filter, Disp.Filters'Length, "Invalid mapping returned for URI: " & URI); end if; end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); -- Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); -- declare -- St : Util.Measures.Stamp; -- begin -- for I in 1 .. 1000 loop -- Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); -- end loop; -- Util.Measures.Report (St, "Find 1000 mapping (extension)"); -- end; -- T.Assert (Map /= null, "No mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); -- declare -- St : Util.Measures.Stamp; -- begin -- for I in 1 .. 1000 loop -- Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); -- end loop; -- Util.Measures.Report (St, "Find 1000 mapping (path)"); -- end; -- -- T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); -- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); -- T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path", Test_Servlet_Path'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Filter", Test_Filter_Mapping'Access); end Add_Tests; end ASF.Servlets.Tests;
Add more servlet mapping tests
Add more servlet mapping tests
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
57c72d506b876db0014353568fab449bc03327d4
src/util-serialize-io.adb
src/util-serialize-io.adb
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Sink.Start_Document; Parser'Class (Handler).Parse (Buffer, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Sink.Start_Document; Parser'Class (Handler).Parse (Stream, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_String) is begin if Value.Is_Null then Stream.Write_Null_Entity (Name); else Stream.Write_Entity (Name, Value.Value); end if; end Write_Entity; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Time) is begin if Value.Is_Null then Stream.Write_Null_Entity (Name); else Stream.Write_Entity (Name, Value.Value); end if; end Write_Entity; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Boolean) is begin if Value.Is_Null then Stream.Write_Null_Entity (Name); else Stream.Write_Entity (Name, Value.Value); end if; end Write_Entity; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Integer) is begin if Value.Is_Null then Stream.Write_Null_Entity (Name); else Stream.Write_Entity (Name, Value.Value); end if; end Write_Entity; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Util.Nullables.Nullable_Long) is begin if Value.Is_Null then Stream.Write_Null_Entity (Name); else Stream.Write_Entity (Name, Integer (Value.Value)); end if; end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Sink.Start_Document; Parser'Class (Handler).Parse (Buffer, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Sink.Start_Document; Parser'Class (Handler).Parse (Stream, Sink); exception -- when Util.Serialize.Mappers.Field_Fatal_Error => -- null; when E : others => if not Handler.Error_Flag then Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end if; end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; end Util.Serialize.IO;
Implement Write_Entity operations on several Nullable types
Implement Write_Entity operations on several Nullable types
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
65e5b20800e7407a5b6afe73577aa9fa9b1cd6fb
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Role_Type range <>) of Ada.Strings.Unbounded.String_Access; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Policy is new Policy with record Names : Role_Name_Array (Role_Type'Range) := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Get the list of role names that are defined by the role map. function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Map_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Declare the Get_Role_Names function
Declare the Get_Role_Names function
Ada
apache-2.0
stcarrez/ada-security
14015e075cd9a0467a0a30b22387669209465c39
awa/src/awa-commands-drivers.adb
awa/src/awa-commands-drivers.adb
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); --if Context.Debug or Context.Verbose or Context.Dump then -- AKT.Configure_Logs (Debug => Context.Debug, -- Dump => Context.Dump, -- Verbose => Context.Verbose); --end if; Context.Load_Configuration; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (Selected.all, To_String (App_Name), Context); Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); --if Context.Debug or Context.Verbose or Context.Dump then -- AKT.Configure_Logs (Debug => Context.Debug, -- Dump => Context.Dump, -- Verbose => Context.Verbose); --end if; if Context.Config_File'Length > 0 then Context.Load_Configuration (Context.Config_File.all); else Context.Load_Configuration (Driver_Name & ".properties"); end if; declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
Update call to Load_Configuration to use the driver's name if no -c <path> option is given
Update call to Load_Configuration to use the driver's name if no -c <path> option is given
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9b58f6a789a7b8356b94b04075e1dc96b844d7ff
bindings/ada/plplot_auxiliary.ads
bindings/ada/plplot_auxiliary.ads
-- $Id$ -- Auxiliary types and subprograms to be with-ed and by all the Ada -- bindings to PLplot -- Copyright (C) 2006-2010 Jerry Bauck -- This file is part of PLplot. -- PLplot is free software; you can redistribute it and/or modify -- it under the terms of the GNU Library General Public License as published -- by the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- PLplot is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Library General Public License for more details. -- You should have received a copy of the GNU Library General Public License -- along with PLplot; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA with Ada.Strings.Bounded, -- fixme Probable cruft. Ada.Strings.Unbounded; use Ada.Strings.Bounded, Ada.Strings.Unbounded; with Ada.Numerics.Long_Real_Arrays; package PLplot_Auxiliary is -------------------------------------------------------------------------------- -- Utility type declarations used by the bindings -- -------------------------------------------------------------------------------- -- Declarations for Ada 95 and Ada 2005 when it is desired to _not_ invoke -- the numerical capability of Annex G.3. -- type Real_Vector is array (Integer range <>) of Long_Float; -- type Real_Matrix is array (Integer range <>, Integer range <>) of Long_Float; -- Declarations when using Ada 2005 and it is desired to invoke the numerics -- Annex G.3 or the user simply prefers to declare real vectors and matrices -- in a manner that is type-compatible with that annex. ALSO IN THIS CASE -- uncomment the line above: with Ada.Numerics.Long_Real_Arrays;. -- Using Annex G.3 requires linking to BLAS and LAPACK libraries or the -- PLplot build process will fail when attempting to link the Ada examples -- e.g. x01a.adb. subtype Real_Vector is Ada.Numerics.Long_Real_Arrays.Real_Vector; subtype Real_Matrix is Ada.Numerics.Long_Real_Arrays.Real_Matrix; ---------------------------------------------------------------------------- -- Implementation note: The easy ability to switch to Ada 2005 Annex G.3 -- capability (with only these simple edits to this file) is the only reason -- for requiring that this package be with-ed in the bindings. Only the -- examples use the utility procedures below--not the bindings themselves. -- If it were ever to be decided to abandon Ada 95 compatibility and to -- require all Ada-capable PLplot builds to link to BLAS and LAPACK, then -- the with-s to this package in the bindings could be removed. ---------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Utility procedures useful in compiling the examples -- -------------------------------------------------------------------------------- -- Mimic C conversion of float to integer; something similar works in e.g. -- plplot_thin.adb. -- C truncates towards 0. Ada rounds to nearest integer; midway rounded -- away from zero, e.g. Inteter(±3.5) is ±4. But any completely reliable -- conversion is probalby not possible; indeed, this one exactly emulates C -- when tested for values around ±2 to ±3. Both convert ±2.9999999999999997 -- to ±2 and ±2.9999999999999998 to ±3. function Trunc(a : Long_Float) return Integer; -- Find minimum in a 1D array. function Vector_Min(x : Real_Vector) return Long_Float; -- Find minimum and its location in a 1D array. procedure Vector_Min(x : Real_Vector; The_Minimum : out Long_Float; Location_Of_Min : out Integer); -- Find maximum in a 1D array. function Vector_Max(x : Real_Vector) return Long_Float; -- Find maximum and its location in a 1D array. procedure Vector_Max(x : Real_Vector; The_Maximum : out Long_Float; Location_Of_Max : out Integer); -- Find minimum in a 2D array. function Matrix_Min(x : Real_Matrix) return Long_Float; -- Find maximum in a 2D array. function Matrix_Max(x : Real_Matrix) return Long_Float; end PLplot_Auxiliary;
-- $Id$ -- Auxiliary types and subprograms to be with-ed and by all the Ada -- bindings to PLplot -- Copyright (C) 2006-2010 Jerry Bauck -- This file is part of PLplot. -- PLplot is free software; you can redistribute it and/or modify -- it under the terms of the GNU Library General Public License as published -- by the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- PLplot is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Library General Public License for more details. -- You should have received a copy of the GNU Library General Public License -- along with PLplot; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA with Ada.Strings.Bounded, -- fixme Probable cruft. Ada.Strings.Unbounded; use Ada.Strings.Bounded, Ada.Strings.Unbounded; -- with Ada.Numerics.Long_Real_Arrays; package PLplot_Auxiliary is -------------------------------------------------------------------------------- -- Utility type declarations used by the bindings -- -------------------------------------------------------------------------------- -- Declarations for Ada 95 and Ada 2005 when it is desired to _not_ invoke -- the numerical capability of Annex G.3. type Real_Vector is array (Integer range <>) of Long_Float; type Real_Matrix is array (Integer range <>, Integer range <>) of Long_Float; -- Declarations when using Ada 2005 and it is desired to invoke the numerics -- Annex G.3 or the user simply prefers to declare real vectors and matrices -- in a manner that is type-compatible with that annex. ALSO IN THIS CASE -- uncomment the line above: with Ada.Numerics.Long_Real_Arrays;. -- Using Annex G.3 requires linking to BLAS and LAPACK libraries or the -- PLplot build process will fail when attempting to link the Ada examples -- e.g. x01a.adb. -- subtype Real_Vector is Ada.Numerics.Long_Real_Arrays.Real_Vector; -- subtype Real_Matrix is Ada.Numerics.Long_Real_Arrays.Real_Matrix; ---------------------------------------------------------------------------- -- Implementation note: The easy ability to switch to Ada 2005 Annex G.3 -- capability (with only these simple edits to this file) is the only reason -- for requiring that this package be with-ed in the bindings. Only the -- examples use the utility procedures below--not the bindings themselves. -- If it were ever to be decided to abandon Ada 95 compatibility and to -- require all Ada-capable PLplot builds to link to BLAS and LAPACK, then -- the with-s to this package in the bindings could be removed. ---------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Utility procedures useful in compiling the examples -- -------------------------------------------------------------------------------- -- Mimic C conversion of float to integer; something similar works in e.g. -- plplot_thin.adb. -- C truncates towards 0. Ada rounds to nearest integer; midway rounded -- away from zero, e.g. Inteter(±3.5) is ±4. But any completely reliable -- conversion is probalby not possible; indeed, this one exactly emulates C -- when tested for values around ±2 to ±3. Both convert ±2.9999999999999997 -- to ±2 and ±2.9999999999999998 to ±3. function Trunc(a : Long_Float) return Integer; -- Find minimum in a 1D array. function Vector_Min(x : Real_Vector) return Long_Float; -- Find minimum and its location in a 1D array. procedure Vector_Min(x : Real_Vector; The_Minimum : out Long_Float; Location_Of_Min : out Integer); -- Find maximum in a 1D array. function Vector_Max(x : Real_Vector) return Long_Float; -- Find maximum and its location in a 1D array. procedure Vector_Max(x : Real_Vector; The_Maximum : out Long_Float; Location_Of_Max : out Integer); -- Find minimum in a 2D array. function Matrix_Min(x : Real_Matrix) return Long_Float; -- Find maximum in a 2D array. function Matrix_Max(x : Real_Matrix) return Long_Float; end PLplot_Auxiliary;
Correct type declarations to once again allow building Ada with an Ada 95 compiler.
Correct type declarations to once again allow building Ada with an Ada 95 compiler. svn path=/trunk/; revision=12890
Ada
lgpl-2.1
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
43effbcfdb8d30933146d795649ad06b3ecbc1ae
mat/src/memory/mat-memory-readers.ads
mat/src/memory/mat-memory-readers.ads
----------------------------------------------------------------------- -- 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 MAT.Types; with MAT.Events; -- with MAT.Ipc; with Util.Events; with MAT.Readers; with MAT.Memory.Targets; -- with MAT.Memory.Clients; -- with MAT.Ipc.Clients; -- with MAT.Events; use MAT.Events; package MAT.Memory.Readers is type Memory_Servant is new MAT.Readers.Reader_Base with record Data : access MAT.Memory.Targets.Target_Memory; -- Slots : Client_Memory_Ref; -- Impl : Client_Memory_Ref; end record; type Memory_Reader_Access is access all Memory_Servant'Class; -- The memory servant is a proxy for the generic communication -- channel to process incomming events (such as memory allocations). 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); -- Register the reader to extract and analyze memory events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access); 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 MAT.Events; with MAT.Readers; with MAT.Memory.Targets; package MAT.Memory.Readers is type Memory_Servant is new MAT.Readers.Reader_Base with record Data : access MAT.Memory.Targets.Target_Memory; end record; type Memory_Reader_Access is access all Memory_Servant'Class; -- The memory servant is a proxy for the generic communication -- channel to process incomming events (such as memory allocations). 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); -- Register the reader to extract and analyze memory events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access); end MAT.Memory.Readers;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5c8291fc705afe5f62acac0eca1e47141b3d50fb
src/asf-applications-main-configs.adb
src/asf-applications-main-configs.adb
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Navigations; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; package body ASF.Applications.Main.Configs is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs"); function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin return Locale; end Get_Locale; -- ------------------------------ -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. -- ------------------------------ procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when TAG_MESSAGE_VAR => N.Name := Value; when TAG_MESSAGE_BUNDLE => declare Bundle : constant String := Util.Beans.Objects.To_String (Value); begin if Util.Beans.Objects.Is_Null (N.Name) then N.App.Register (Name => Bundle & "Msg", Bundle => Bundle); else N.App.Register (Name => Util.Beans.Objects.To_String (N.Name), Bundle => Bundle); end if; N.Name := Util.Beans.Objects.Null_Object; end; when TAG_DEFAULT_LOCALE => declare L : Util.Locales.Locale := Get_Locale (Value); begin N.App.Set_Default_Locale (L); end; when TAG_SUPPORTED_LOCALE => null; end case; end Set_Member; AMapper : aliased Application_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. -- ------------------------------ package body Reader_Config is -- Get the navigation handler for the Navigation_Config instantiation -- GNAT crashes if the call is made in the instantation part. Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access, Context.all'Access); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access, Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); Config : aliased Application_Config; begin -- Install the property context that gives access -- to the application configuration properties Prop_Context.Set_Properties (App.Conf); Context.Set_Resolver (Prop_Context'Unchecked_Access); Reader.Add_Mapping ("faces-config", AMapper'Access); Reader.Add_Mapping ("module", AMapper'Access); Reader.Add_Mapping ("web-app", AMapper'Access); Config.App := App; Application_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; -- ------------------------------ -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String) is Reader : Util.Serialize.IO.XML.Parser; Context : aliased EL.Contexts.Default.Default_Context; -- Setup the <b>Reader</b> to parse and build the configuration for managed beans, -- navigation rules, servlet rules. Each package instantiation creates a local variable -- used while parsing the XML file. package Config is new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access); pragma Warnings (Off, Config); begin Log.Info ("Reading module configuration file {0}", File); -- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access, Default => PARAM_VALUE'Access); -- ------------------------------ -- Returns the configuration parameter. -- ------------------------------ function P return Config_Param is begin return Param; end P; end Parameter; begin AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR); AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE); AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE); AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE); end ASF.Applications.Main.Configs;
----------------------------------------------------------------------- -- applications-main-configs -- Configuration support for ASF Applications -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Navigations; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; package body ASF.Applications.Main.Configs is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main.Configs"); function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale; function Get_Locale (Value : in Util.Beans.Objects.Object) return Util.Locales.Locale is Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin return Locale; end Get_Locale; -- ------------------------------ -- Save in the application config object the value associated with the given field. -- When the <b>TAG_MESSAGE_BUNDLE</b> field is reached, insert the new bundle definition -- in the application. -- ------------------------------ procedure Set_Member (N : in out Application_Config; Field : in Application_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when TAG_MESSAGE_VAR => N.Name := Value; when TAG_MESSAGE_BUNDLE => declare Bundle : constant String := Util.Beans.Objects.To_String (Value); begin if Util.Beans.Objects.Is_Null (N.Name) then N.App.Register (Name => Bundle & "Msg", Bundle => Bundle); else N.App.Register (Name => Util.Beans.Objects.To_String (N.Name), Bundle => Bundle); end if; N.Name := Util.Beans.Objects.Null_Object; end; when TAG_DEFAULT_LOCALE => N.App.Set_Default_Locale (Get_Locale (Value)); when TAG_SUPPORTED_LOCALE => N.App.Add_Supported_Locale (Get_Locale (Value)); end case; end Set_Member; AMapper : aliased Application_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- By instantiating this package, the <b>Reader</b> gets populated with the XML mappings -- to read the servlet, managed beans and navigation rules. -- ------------------------------ package body Reader_Config is -- Get the navigation handler for the Navigation_Config instantiation -- GNAT crashes if the call is made in the instantation part. Nav : constant ASF.Navigations.Navigation_Handler_Access := App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, App.Factory'Access, Context.all'Access); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav, Context.all'Access); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, App.all'Access, Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); Config : aliased Application_Config; begin -- Install the property context that gives access -- to the application configuration properties Prop_Context.Set_Properties (App.Conf); Context.Set_Resolver (Prop_Context'Unchecked_Access); Reader.Add_Mapping ("faces-config", AMapper'Access); Reader.Add_Mapping ("module", AMapper'Access); Reader.Add_Mapping ("web-app", AMapper'Access); Config.App := App; Application_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; -- ------------------------------ -- Read the configuration file associated with the application. This includes: -- <ul> -- <li>The servlet and filter mappings</li> -- <li>The managed bean definitions</li> -- <li>The navigation rules</li> -- </ul> -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String) is Reader : Util.Serialize.IO.XML.Parser; Context : aliased EL.Contexts.Default.Default_Context; -- Setup the <b>Reader</b> to parse and build the configuration for managed beans, -- navigation rules, servlet rules. Each package instantiation creates a local variable -- used while parsing the XML file. package Config is new Reader_Config (Reader, App'Unchecked_Access, Context'Unchecked_Access); pragma Warnings (Off, Config); begin Log.Info ("Reading module configuration file {0}", File); -- Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is PARAM_NAME : aliased constant String := Name; PARAM_VALUE : aliased constant String := Default; Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access, Default => PARAM_VALUE'Access); -- ------------------------------ -- Returns the configuration parameter. -- ------------------------------ function P return Config_Param is begin return Param; end P; end Parameter; begin AMapper.Add_Mapping ("application/message-bundle/@var", TAG_MESSAGE_VAR); AMapper.Add_Mapping ("application/message-bundle", TAG_MESSAGE_BUNDLE); AMapper.Add_Mapping ("application/locale-config/default-locale", TAG_DEFAULT_LOCALE); AMapper.Add_Mapping ("application/locale-config/supported-locale", TAG_SUPPORTED_LOCALE); end ASF.Applications.Main.Configs;
Add the supported locales on the application
Add the supported locales on the application
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
316863c25e7bf80783b83f56288049c819550e43
src/asf-components-widgets-inputs.ads
src/asf-components-widgets-inputs.ads
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; package ASF.Components.Widgets.Inputs is use ASF.Contexts.Faces; use ASF.Contexts.Writer; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <dl class='... awa-error'> -- <dt>title <i>required</i></dt> -- <dd><input type='text' ...> <em/> -- <span class='...'>message</span> -- </dd> -- </dl> type UIInput is new ASF.Components.Html.Forms.UIInput with null record; type UIInput_Access is access all UIInput'Class; -- Render the input field title. procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class); -- ------------------------------ -- The auto complete component. -- ------------------------------ -- type UIComplete is new UIInput with private; type UIComplete_Access is access all UIInput'Class; -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class); private type UIComplete is new UIInput with record Match_Value : Util.Beans.Objects.Object; end record; end ASF.Components.Widgets.Inputs;
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; package ASF.Components.Widgets.Inputs is use ASF.Contexts.Faces; use ASF.Contexts.Writer; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <dl class='... awa-error'> -- <dt>title <i>required</i></dt> -- <dd><input type='text' ...> <em/> -- <span class='...'>message</span> -- </dd> -- </dl> type UIInput is new ASF.Components.Html.Forms.UIInput with null record; type UIInput_Access is access all UIInput'Class; -- Render the input field title. procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class); -- ------------------------------ -- The auto complete component. -- ------------------------------ -- type UIComplete is new UIInput with private; type UIComplete_Access is access all UIInput'Class; -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class); -- ------------------------------ -- The input date component. -- ------------------------------ -- type UIInputDate is new UIInput with null record; type UIInputDate_Access is access all UIInputDate'Class; -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in UIInputDate; Context : in out Faces_Context'Class); private type UIComplete is new UIInput with record Match_Value : Util.Beans.Objects.Object; end record; end ASF.Components.Widgets.Inputs;
Declare the inputDate component
Declare the inputDate component
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
50e9c040b6e1e403d9d357f52bd0b5a25440fa7e
src/postgresql/ado-drivers-connections-postgresql.ads
src/postgresql/ado-drivers-connections-postgresql.ads
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with PQ; package ADO.Drivers.Connections.Postgresql is type Postgresql_Driver is limited private; -- Initialize the Postgresql driver. procedure Initialize; private -- Create a new Postgresql connection using the configuration parameters. procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Postgresql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Postgresql driver. overriding procedure Finalize (D : in out Postgresql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String; Server_Name : Unbounded_String; Login_Name : Unbounded_String; Password : Unbounded_String; Server : PQ.PGconn_Access := PQ.Null_PGconn; Connected : Boolean := False; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Create the database and initialize it with the schema SQL file. overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Drivers.Connections.Postgresql;
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with PQ; package ADO.Drivers.Connections.Postgresql is type Postgresql_Driver is limited private; -- Initialize the Postgresql driver. procedure Initialize; private -- Create a new Postgresql connection using the configuration parameters. procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Postgresql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. overriding procedure Create_Database (D : in out Postgresql_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Deletes the Postgresql driver. overriding procedure Finalize (D : in out Postgresql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String; Server_Name : Unbounded_String; Login_Name : Unbounded_String; Password : Unbounded_String; Server : PQ.PGconn_Access := PQ.Null_PGconn; Connected : Boolean := False; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); end ADO.Drivers.Connections.Postgresql;
Move the Create_Database operation on the Driver instead of the database connection
Move the Create_Database operation on the Driver instead of the database connection
Ada
apache-2.0
stcarrez/ada-ado
7a1cdd9d7678a142ae9b0de875f4a4c8ea2dd94e
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; if Event.Index = MAT.Events.MSG_MALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Index = MAT.Events.MSG_REALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Alloc_Size + Event.Old_Size; else Info.Free_Size := Info.Alloc_Size + Event.Size; end if; end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Last_Event := Event; Info.Count := 1; if Event.Index = MAT.Events.MSG_MALLOC then Info.Alloc_Size := Event.Size; elsif Event.Index = MAT.Events.MSG_REALLOC then Info.Alloc_Size := Event.Size; Info.Free_Size := Event.Old_Size; else Info.Free_Size := Event.Size; end if; Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Natural; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; begin for I in Backtrace'Range loop exit when I > Depth; Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Last_Event := Event; Info.Frame_Addr := Key.Addr; Info.Count := 1; Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; if Event.Index = MAT.Events.MSG_MALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Index = MAT.Events.MSG_REALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Alloc_Size + Event.Old_Size; else Info.Free_Size := Info.Alloc_Size + Event.Size; end if; end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Natural; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; begin for I in Backtrace'Range loop exit when I > Depth; Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
Use MAT.Events.Tools.Collect_Info to collect the information about events
Use MAT.Events.Tools.Collect_Info to collect the information about events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b4b5ae44894cdd3db063908f5fd40e364a7b8601
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- 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 Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with EL.Objects; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use EL.Objects; Factory : ASF.Applications.Main.Application_Factory; App : Applications.Main.Application; Conf : Applications.Config; begin Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); Conf.Set ("view.dir", "."); Conf.Set ("view.file_ext", ""); App.Initialize (Conf, Factory); loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin if Pos > 0 then App.Set_Global (Name => Value (Value'First .. Pos - 1), Value => To_Object (Value (Pos + 1 .. Value'Last))); else App.Set_Global (Name => Value (Value'First .. Pos - 1), Value => To_Object (True)); end if; end; when others => exit; end case; end loop; declare View_Name : constant String := Get_Argument; Pos : constant Natural := Index (View_Name, "."); Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin if View_Name = "" or Pos = 0 then Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file"); Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml"); return; end if; Req.Set_Method ("GET"); Req.Set_Request_URI (View_Name (View_Name'First .. Pos - 1)); App.Dispatch (Page => View_Name (View_Name'First .. Pos - 1), Request => Req, Response => Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Servlets; with ASF.Servlets.Faces; with ASF.Server; with EL.Objects; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use EL.Objects; Factory : ASF.Applications.Main.Application_Factory; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; App : aliased Applications.Main.Application; Conf : Applications.Config; Container : ASF.Server.Container; begin Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); Conf.Set ("view.dir", "./"); Conf.Set ("view.file_ext", ""); App.Initialize (Conf, Factory); App.Add_Servlet (Name => "file", Server => Faces'Unchecked_Access); App.Add_Mapping ("*.xhtml", "file"); Container.Register_Application ("/render", App'Unchecked_Access); loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin if Pos > 0 then App.Set_Global (Name => Value (Value'First .. Pos - 1), Value => To_Object (Value (Pos + 1 .. Value'Last))); else App.Set_Global (Name => Value (Value'First .. Pos - 1), Value => To_Object (True)); end if; end; when others => exit; end case; end loop; declare View_Name : constant String := Get_Argument; Pos : constant Natural := Index (View_Name, "."); Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin if View_Name = "" or Pos = 0 then Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file"); Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml"); return; end if; Req.Set_Method ("GET"); Req.Set_Request_URI ("/render/" & View_Name); -- View_Name (View_Name'First .. Pos - 1) & ".html"); Container.Service (Req, Reply); Reply.Read_Content (Content); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content)); exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Fix the render example so that it works with the new ASF routes
Fix the render example so that it works with the new ASF routes
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1b9777a92c4634f7ad50f9977e55066465f1027e
src/http/curl/util-http-clients-curl.ads
src/http/curl/util-http-clients-curl.ads
----------------------------------------------------------------------- -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- 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); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; 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 System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- 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); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; end Util.Http.Clients.Curl;
Declare and override the Do_Put procedure
Declare and override the Do_Put procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f9ac458b7c80864696d0ef8e562a79e644caf9a4
src/orka/implementation/orka-cameras.adb
src/orka/implementation/orka-cameras.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.Tags.Generic_Dispatching_Constructor; with Orka.SIMD; with Orka.Transforms.Singles.Vectors; with Orka.Types; package body Orka.Cameras is package Vector_Transforms renames Orka.Transforms.Singles.Vectors; function Clamp_Distance is new Orka.Types.Clamp (GL.Types.Single, Distance); function Normalize_Angle is new Orka.Types.Normalize_Periodic (GL.Types.Single, Angle); procedure Set_FOV (Object : in out Camera_Lens; FOV : GL.Types.Single) is begin Object.FOV := FOV; end Set_FOV; function FOV (Object : Camera_Lens) return GL.Types.Single is (Object.FOV); function Projection_Matrix (Object : Camera_Lens) return Transforms.Matrix4 is Width : constant GL.Types.Single := GL.Types.Single (Object.Width); Height : constant GL.Types.Single := GL.Types.Single (Object.Height); begin return Transforms.Infinite_Perspective_Reversed_Z (Object.FOV, Width / Height, 0.1); end Projection_Matrix; ----------------------------------------------------------------------------- procedure Set_Position (Object : in out First_Person_Camera; Position : Transforms.Vector4) is begin Object.Position := Position; end Set_Position; procedure Set_Orientation (Object : in out Look_From_Camera; Roll, Pitch, Yaw : Angle) is begin Object.Roll := Roll; Object.Pitch := Pitch; Object.Yaw := Yaw; end Set_Orientation; overriding procedure Look_At (Object : in out Look_At_Camera; Target : Behaviors.Behavior_Ptr) is begin Object.Target := Target; end Look_At; procedure Set_Up_Direction (Object : in out Look_At_Camera; Direction : Transforms.Vector4) is begin Object.Up := Direction; end Set_Up_Direction; overriding procedure Look_At (Object : in out Third_Person_Camera; Target : Behaviors.Behavior_Ptr) is begin Object.Target := Target; end Look_At; procedure Set_Angles (Object : in out Rotate_Around_Camera; Alpha : Angle; Beta : Angle) is begin Object.Alpha := Alpha; Object.Beta := Beta; end Set_Angles; procedure Set_Radius (Object : in out Rotate_Around_Camera; Radius : Distance) is begin Object.Radius := Radius; end Set_Radius; procedure Set_Radius (Object : in out Follow_Camera; Radius : Distance) is begin Object.Radius := Radius; end Set_Radius; procedure Set_Height (Object : in out Follow_Camera; Height : Distance) is begin Object.Height := Height; end Set_Height; procedure Set_Direction (Object : in out Follow_Camera; Direction : Angle) is begin Object.Direction := Direction; end Set_Direction; ----------------------------------------------------------------------------- overriding procedure Update (Object : in out Look_From_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); if Using_Camera then Object.Yaw := Normalize_Angle (Object.Yaw + Object.Input.Delta_X); Object.Pitch := Normalize_Angle (Object.Pitch + Object.Input.Delta_Y); end if; end Update; -- Look_At camera does not need to implement Update because the -- view matrix does not depend on the pointer (it is computed using -- the camera's and target's positions) overriding procedure Update (Object : in out Rotate_Around_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); if Using_Camera then Object.Alpha := Normalize_Angle (Object.Alpha + Object.Input.Delta_X); Object.Beta := Normalize_Angle (Object.Beta + Object.Input.Delta_Y); end if; Object.Radius := Clamp_Distance (Object.Radius - Object.Input.Scroll_Y); end Update; overriding procedure Update (Object : in out Follow_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); -- TODO end Update; ----------------------------------------------------------------------------- overriding function View_Matrix (Object : Look_From_Camera) return Transforms.Matrix4 is use Transforms; begin return Ry (Object.Roll) * Rx (Object.Pitch) * Ry (Object.Yaw); end View_Matrix; overriding function View_Matrix (Object : Look_At_Camera) return Transforms.Matrix4 is use Vector_Transforms; use Orka.SIMD; Forward : constant Vector4 := Normalize (Object.Target.Position - Object.Position); Side : constant Vector4 := Cross (Forward, Object.Up); Up : constant Vector4 := Cross (Side, Forward); begin return ((Side (X), Up (X), -Forward (X), 0.0), (Side (Y), Up (Y), -Forward (Y), 0.0), (Side (Z), Up (Z), -Forward (Z), 0.0), (0.0, 0.0, 0.0, 1.0)); end View_Matrix; overriding function View_Matrix (Object : Rotate_Around_Camera) return Transforms.Matrix4 is use Transforms; begin return (0.0, 0.0, -Object.Radius, 0.0) + Rx (Object.Beta) * Ry (Object.Alpha); end View_Matrix; overriding function View_Matrix (Object : Follow_Camera) return Transforms.Matrix4 is begin -- TODO return Transforms.Identity_Value; end View_Matrix; ----------------------------------------------------------------------------- overriding function View_Position (Object : First_Person_Camera) return Transforms.Vector4 is (Object.Position); overriding function View_Position (Object : Third_Person_Camera) return Transforms.Vector4 is (Object.Target.Position); ----------------------------------------------------------------------------- function Create_Lens (Width, Height : Positive; FOV : GL.Types.Single; Context : Contexts.Context) return Camera_Lens'Class is begin return Result : Camera_Lens (Width, Height) do Result.FOV := FOV; end return; end Create_Lens; ----------------------------------------------------------------------------- Kind_To_Tag : constant array (Camera_Kind) of Ada.Tags.Tag := (Look_From => Look_From_Camera'Tag, Look_At => Look_At_Camera'Tag, Rotate_Around => Rotate_Around_Camera'Tag, Follow => Follow_Camera'Tag); overriding function Create_Camera (Parameters : not null access Parameter_Record) return Look_From_Camera is begin return Look_From_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Look_At_Camera is begin return Look_At_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Rotate_Around_Camera is begin return Rotate_Around_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Follow_Camera is begin return Follow_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; function Create_Camera (Kind : Camera_Kind; Input : Inputs.Pointer_Input_Ptr; Lens : Lens_Ptr; FB : Rendering.Framebuffers.Framebuffer_Ptr) return Camera'Class is function Create is new Ada.Tags.Generic_Dispatching_Constructor (Camera, Parameter_Record, Create_Camera); Parameters : aliased Parameter_Record := (Input, Lens, FB); begin return Create (Kind_To_Tag (Kind), Parameters'Access); end Create_Camera; end Orka.Cameras;
-- 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.Tags.Generic_Dispatching_Constructor; with Orka.SIMD; with Orka.Transforms.Singles.Vectors; with Orka.Types; package body Orka.Cameras is package Vector_Transforms renames Orka.Transforms.Singles.Vectors; function Clamp_Distance is new Orka.Types.Clamp (GL.Types.Single, Distance); function Normalize_Angle is new Orka.Types.Normalize_Periodic (GL.Types.Single, Angle); procedure Set_FOV (Object : in out Camera_Lens; FOV : GL.Types.Single) is begin Object.FOV := FOV; end Set_FOV; function FOV (Object : Camera_Lens) return GL.Types.Single is (Object.FOV); function Projection_Matrix (Object : Camera_Lens) return Transforms.Matrix4 is Width : constant GL.Types.Single := GL.Types.Single (Object.Width); Height : constant GL.Types.Single := GL.Types.Single (Object.Height); begin return Transforms.Infinite_Perspective_Reversed_Z (Object.FOV, Width / Height, 0.1); end Projection_Matrix; ----------------------------------------------------------------------------- procedure Set_Position (Object : in out First_Person_Camera; Position : Transforms.Vector4) is begin Object.Position := Position; end Set_Position; procedure Set_Orientation (Object : in out Look_From_Camera; Roll, Pitch, Yaw : Angle) is begin Object.Roll := Roll; Object.Pitch := Pitch; Object.Yaw := Yaw; end Set_Orientation; overriding procedure Look_At (Object : in out Look_At_Camera; Target : Behaviors.Behavior_Ptr) is begin Object.Target := Target; end Look_At; procedure Set_Up_Direction (Object : in out Look_At_Camera; Direction : Transforms.Vector4) is begin Object.Up := Direction; end Set_Up_Direction; overriding procedure Look_At (Object : in out Third_Person_Camera; Target : Behaviors.Behavior_Ptr) is begin Object.Target := Target; end Look_At; procedure Set_Angles (Object : in out Rotate_Around_Camera; Alpha : Angle; Beta : Angle) is begin Object.Alpha := Alpha; Object.Beta := Beta; end Set_Angles; procedure Set_Radius (Object : in out Rotate_Around_Camera; Radius : Distance) is begin Object.Radius := Radius; end Set_Radius; procedure Set_Radius (Object : in out Follow_Camera; Radius : Distance) is begin Object.Radius := Radius; end Set_Radius; procedure Set_Height (Object : in out Follow_Camera; Height : Distance) is begin Object.Height := Height; end Set_Height; procedure Set_Direction (Object : in out Follow_Camera; Direction : Angle) is begin Object.Direction := Direction; end Set_Direction; ----------------------------------------------------------------------------- overriding procedure Update (Object : in out Look_From_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); if Using_Camera then Object.Yaw := Normalize_Angle (Object.Yaw + Object.Input.Delta_X); Object.Pitch := Normalize_Angle (Object.Pitch + Object.Input.Delta_Y); end if; end Update; -- Look_At camera does not need to implement Update because the -- view matrix does not depend on the pointer (it is computed using -- the camera's and target's positions) overriding procedure Update (Object : in out Rotate_Around_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); if Using_Camera then Object.Alpha := Normalize_Angle (Object.Alpha + Object.Input.Delta_X); Object.Beta := Normalize_Angle (Object.Beta + Object.Input.Delta_Y); end if; Object.Radius := Clamp_Distance (Object.Radius - Object.Input.Scroll_Y); end Update; overriding procedure Update (Object : in out Follow_Camera; Delta_Time : Duration) is Using_Camera : constant Boolean := Object.Input.Button_Pressed (Orka.Inputs.Right); begin Object.Input.Lock_Pointer (Using_Camera); -- TODO end Update; ----------------------------------------------------------------------------- overriding function View_Matrix (Object : Look_From_Camera) return Transforms.Matrix4 is use Transforms; begin return Ry (Object.Roll) * Rx (Object.Pitch) * Ry (Object.Yaw); end View_Matrix; overriding function View_Matrix (Object : Look_At_Camera) return Transforms.Matrix4 is use Vector_Transforms; use Transforms; use Orka.SIMD; Rotate_To_GL : constant Matrix4 := Ry (-90.0) * Rx (-90.0); Forward : constant Vector_Type := Normalize (Rotate_To_GL * (Object.Target.Position - Object.Position)); Side : constant Vector_Type := Cross (Forward, Object.Up); Up : constant Vector_Type := Cross (Side, Forward); begin return ((Side (X), Up (X), -Forward (X), 0.0), (Side (Y), Up (Y), -Forward (Y), 0.0), (Side (Z), Up (Z), -Forward (Z), 0.0), (0.0, 0.0, 0.0, 1.0)); end View_Matrix; overriding function View_Matrix (Object : Rotate_Around_Camera) return Transforms.Matrix4 is use Transforms; begin return (0.0, 0.0, -Object.Radius, 0.0) + Rx (Object.Beta) * Ry (Object.Alpha); end View_Matrix; overriding function View_Matrix (Object : Follow_Camera) return Transforms.Matrix4 is begin -- TODO return Transforms.Identity_Value; end View_Matrix; ----------------------------------------------------------------------------- overriding function View_Position (Object : First_Person_Camera) return Transforms.Vector4 is (Object.Position); overriding function View_Position (Object : Third_Person_Camera) return Transforms.Vector4 is (Object.Target.Position); ----------------------------------------------------------------------------- function Create_Lens (Width, Height : Positive; FOV : GL.Types.Single; Context : Contexts.Context) return Camera_Lens'Class is begin return Result : Camera_Lens (Width, Height) do Result.FOV := FOV; end return; end Create_Lens; ----------------------------------------------------------------------------- Kind_To_Tag : constant array (Camera_Kind) of Ada.Tags.Tag := (Look_From => Look_From_Camera'Tag, Look_At => Look_At_Camera'Tag, Rotate_Around => Rotate_Around_Camera'Tag, Follow => Follow_Camera'Tag); overriding function Create_Camera (Parameters : not null access Parameter_Record) return Look_From_Camera is begin return Look_From_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Look_At_Camera is begin return Look_At_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Rotate_Around_Camera is begin return Rotate_Around_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; overriding function Create_Camera (Parameters : not null access Parameter_Record) return Follow_Camera is begin return Follow_Camera'(Camera with Input => Parameters.Input, Lens => Parameters.Lens, FB => Parameters.FB, others => <>); end Create_Camera; function Create_Camera (Kind : Camera_Kind; Input : Inputs.Pointer_Input_Ptr; Lens : Lens_Ptr; FB : Rendering.Framebuffers.Framebuffer_Ptr) return Camera'Class is function Create is new Ada.Tags.Generic_Dispatching_Constructor (Camera, Parameter_Record, Create_Camera); Parameters : aliased Parameter_Record := (Input, Lens, FB); begin return Create (Kind_To_Tag (Kind), Parameters'Access); end Create_Camera; end Orka.Cameras;
Fix function View_Matrix of Look_At camera
orka: Fix function View_Matrix of Look_At camera Function Position of interface Behavior returns positions in the structural frame (X = aft, Y = right, Z = top), not in OpenGL (X = right, Y = top, Z = aft). Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
ad2daf98cb80fb425c86a4927ea73ce16b752333
src/wiki-helpers-parser.ads
src/wiki-helpers-parser.ads
----------------------------------------------------------------------- -- wiki-helpers-parser -- Generic procedure for the wiki parser -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; generic type Engine_Type is limited private; type Element_Type is limited private; with function Element (Item : in Element_Type; Pos : in Natural) return Wiki.Strings.WChar is <>; with function Length (Item : in Element_Type) return Natural is <>; with procedure Parse (Engine : in out Engine_Type; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document) is <>; procedure Wiki.Helpers.Parser (Engine : in out Engine_Type; Content : in Element_Type; Doc : in out Wiki.Documents.Document); pragma Preelaborate (Wiki.Helpers.Parser);
----------------------------------------------------------------------- -- wiki-helpers-parser -- Generic procedure for the wiki parser -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; generic type Engine_Type is limited private; type Element_Type (<>) is limited private; with procedure Element (Item : in Element_Type; Pos : in out Natural; Char : out Wiki.Strings.WChar) is <>; with function Length (Item : in Element_Type) return Natural is <>; with procedure Parse (Engine : in out Engine_Type; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document) is <>; procedure Wiki.Helpers.Parser (Engine : in out Engine_Type; Content : in Element_Type; Doc : in out Wiki.Documents.Document); pragma Preelaborate (Wiki.Helpers.Parser);
Change the Element operation to a procedure that gets and updates the position
Change the Element operation to a procedure that gets and updates the position
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
25e444b811656485a90cdce5a3c3fdedf607da39
src/sys/encoders/util-encoders-hmac-sha1.adb
src/sys/encoders/util-encoders-hmac-sha1.adb
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base16; with Util.Encoders.Base64; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package body Util.Encoders.HMAC.SHA1 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA1.Hash_Array; 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-SHA1 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest is Ctx : Context; Result : Util.Encoders.SHA1.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-SHA1 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.SHA1.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA1.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 use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; begin -- Reduce the key if Key'Length > 64 then Util.Encoders.SHA1.Update (E.SHA, Key); Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19)); E.Key_Len := 19; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA1 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.SHA1.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.SHA1.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.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Hash_Array) is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; begin Util.Encoders.SHA1.Finish (E.SHA, Hash); -- Hash the key in the SHA1 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.SHA1.Update (E.SHA, Block); end; Util.Encoders.SHA1.Update (E.SHA, Hash); Util.Encoders.SHA1.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Digest) is H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base16.Encoder; begin Finish (E, H); B.Convert (H, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Base64_Digest; URL : in Boolean := False) is H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base64.Encoder; begin Finish (E, H); B.Set_URL_Mode (URL); B.Convert (H, Hash); end Finish_Base64; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is begin null; end Transform; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA1;
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- Copyright (C) 2011, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base16; with Util.Encoders.Base64; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package body Util.Encoders.HMAC.SHA1 is -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 code in binary. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array is Ctx : Context; Result : Util.Encoders.SHA1.Hash_Array; 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-SHA1 code as hexadecimal string. -- ------------------------------ function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Digest is Ctx : Context; Result : Util.Encoders.SHA1.Digest; 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.SHA1.Hash_Array) is Ctx : Context; begin Set_Key (Ctx, Key); Update (Ctx, Data); Finish (Ctx, Result); end Sign; -- ------------------------------ -- Sign the data string with the key and return the HMAC-SHA1 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.SHA1.Base64_Digest is Ctx : Context; Result : Util.Encoders.SHA1.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.SHA1.Update (E.SHA, Key); Util.Encoders.SHA1.Finish (E.SHA, E.Key (0 .. 19)); E.Key_Len := 19; else E.Key_Len := Key'Length - 1; E.Key (0 .. E.Key_Len) := Key; end if; -- Hash the key in the SHA1 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.SHA1.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.SHA1.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.SHA1.Update (E.SHA, S); end Update; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Hash_Array) is begin Util.Encoders.SHA1.Finish (E.SHA, Hash); -- Hash the key in the SHA1 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.SHA1.Update (E.SHA, Block); end; Util.Encoders.SHA1.Update (E.SHA, Hash); Util.Encoders.SHA1.Finish (E.SHA, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Digest) is H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base16.Encoder; begin Finish (E, H); B.Convert (H, Hash); end Finish; -- ------------------------------ -- Computes the HMAC-SHA1 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.SHA1.Base64_Digest; URL : in Boolean := False) is H : Util.Encoders.SHA1.Hash_Array; B : Util.Encoders.Base64.Encoder; begin Finish (E, H); B.Set_URL_Mode (URL); B.Convert (H, Hash); end Finish_Base64; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is begin null; end Transform; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context) is begin null; end Initialize; end Util.Encoders.HMAC.SHA1;
Implement Sign procedure for PBKDF2
Implement Sign procedure for PBKDF2
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9f14dc44f11a3716cf7d990c02fbc338af70b23e
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Introduction == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by [http://code.google.com/p/ada-gen Dynamo] to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by [http://code.google.com/p/ada-gen Dynamo]. -- -- == XML Query File and Mapping == -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- == SQL Result Mapping == -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify and table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
Use a private with clause for Interfaces
Use a private with clause for Interfaces
Ada
apache-2.0
stcarrez/ada-ado
846e48b294ffc5d106e35a1f96884f65e2082c60
src/babel_main.adb
src/babel_main.adb
with GNAT.IO; use GNAT.IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; procedure babel_main is use Ada.Strings.Unbounded; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pools.Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Do_Backup (Count : in Positive) is Workers : Babel.Strategies.Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access); Backup.Scan (Queue, Container); end Do_Backup; begin Dir := Babel.Files.Allocate (Name => ".", Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Store.Set_Root_Directory ("/tmp/babel-store"); Local.Set_Root_Directory ("."); Backup.Set_Filters (Exclude'Unchecked_Access); Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Backup.Set_Buffers (Buffers'Unchecked_Access); Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size)); Do_Backup (2); -- Bkp.Files.Scan (".", Dir); -- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access); -- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size)); -- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files)); -- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs)); end babel_main;
with GNAT.IO; use GNAT.IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Util.Log.Loggers; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; with Babel.Base.Text; with Babel.Base.Users; with Babel.Streams; with Babel.Streams.XZ; with Babel.Streams.Cached; with Babel.Streams.Files; with Tar; procedure babel_main is use Ada.Strings.Unbounded; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; Database : aliased Babel.Base.Text.Text_Database; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Do_Backup (Count : in Positive) is Workers : Babel.Strategies.Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Babel.Strategies.Workers.Start (Workers, Backup'Unchecked_Access); Backup.Scan (Queue, Container); end Do_Backup; begin Util.Log.Loggers.Initialize ("babel.properties"); Dir := Babel.Files.Allocate (Name => ".", Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Store.Set_Root_Directory ("/tmp/babel-store"); Local.Set_Root_Directory ("."); Backup.Set_Filters (Exclude'Unchecked_Access); Backup.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Backup.Set_Buffers (Buffers'Unchecked_Access); Backup.Set_Database (Database'Unchecked_Access); Put_Line ("Size: " & Natural'Image (Ada.Directories.File_Size'Size)); Do_Backup (2); Database.Save ("database.txt"); -- Bkp.Files.Scan (".", Dir); -- Bkp.Files.Iterate_Files (".", Dir, 10, Print_Sha'Access); -- Put_Line ("Total size: " & Ada.Directories.File_Size'Image (Dir.Tot_Size)); -- Put_Line ("File count: " & Natural'Image (Dir.Tot_Files)); -- Put_Line ("Dir count: " & Natural'Image (Dir.Tot_Dirs)); end babel_main;
Update the main for a simple backup
Update the main for a simple backup
Ada
apache-2.0
stcarrez/babel
e08d3f12b4bbb063e31d5bb45898f06efcf78099
regtests/ado-datasets-tests.adb
regtests/ado-datasets-tests.adb
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Regtests.Simple.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List", Test_List'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Data : ADO.Datasets.Dataset; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100, Data.Get_Count, "Invalid dataset size"); end Test_List; end ADO.Datasets.Tests;
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with Regtests.Simple.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count", Test_Count'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Data : ADO.Datasets.Dataset; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100, Data.Get_Count, "Invalid dataset size"); end Test_List; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; end ADO.Datasets.Tests;
Add a test for Get_Count function
Add a test for Get_Count function
Ada
apache-2.0
stcarrez/ada-ado
f92db01a316ee3ac26908f55cf18ef097ad0b7f1
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean is begin if Node.Node = null then return False; else return Is_Selected (Node.Node.all, Context); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Context); when N_AND => return Is_Selected (Node.Left.all, Context) and then Is_Selected (Node.Right.all, Context); when N_OR => return Is_Selected (Node.Left.all, Context) or else Is_Selected (Node.Right.all, Context); when N_RANGE_SIZE => return Context.Allocation.Size >= Node.Min_Size and Context.Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Context.Addr >= Node.Min_Addr and Context.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Context.Allocation.Time >= Node.Min_Time and Context.Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return False; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; end MAT.Expressions;
Update the Is_Selected operation to pass the slot address and allocation as parameter
Update the Is_Selected operation to pass the slot address and allocation as parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
44c82a1453492b38ac9e3bc9856621eea543e009
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; -- 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 := '/'; 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; type File_Type is new Integer; -- 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 NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Integer := 4; FD_CLOEXEC : constant Integer := 1; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := 8#000#; O_WRONLY : constant Interfaces.C.int := 8#001#; O_RDWR : constant Interfaces.C.int := 8#002#; O_CREAT : constant Interfaces.C.int := 8#100#; O_EXCL : constant Interfaces.C.int := 8#200#; O_TRUNC : constant Interfaces.C.int := 8#1000#; O_APPEND : constant Interfaces.C.int := 8#2000#; 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; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "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; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Integer; Flags : in Integer) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; -- 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 := '/'; 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; type File_Type is new Integer; -- 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 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; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "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; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); end Util.Systems.Os;
Use the Util.Systems.Constants generated package for some definitions
Use the Util.Systems.Constants generated package for some definitions
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
568a267cd353b8982eee7f13b9cbcc39dc5c59d6
testutil/util-tests-servers.ads
testutil/util-tests-servers.ads
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- 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.Finalization; package Util.Tests.Servers is -- Pool of objects type Server is new Ada.Finalization.Limited_Controlled with private; type Server_Access is access all Server'Class; -- Get the server port. function Get_Port (From : in Server) return Natural; -- Process the line received by the server. procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String); -- Start the server task. procedure Start (S : in out Server); private -- A small server that listens to HTTP requests and replies with fake -- responses. This server is intended to be used by unit tests and not to serve -- real pages. task type Server_Task is entry Start (S : in Server_Access); -- entry Stop; end Server_Task; type Server is new Ada.Finalization.Limited_Controlled with record Port : Natural := 0; Need_Shutdown : Boolean := False; Server : Server_Task; end record; end Util.Tests.Servers;
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- 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.Finalization; package Util.Tests.Servers is -- A small TCP/IP server for unit tests. type Server is new Ada.Finalization.Limited_Controlled with private; type Server_Access is access all Server'Class; -- Get the server port. function Get_Port (From : in Server) return Natural; -- Process the line received by the server. procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String); -- Start the server task. procedure Start (S : in out Server); private -- A small server that listens to HTTP requests and replies with fake -- responses. This server is intended to be used by unit tests and not to serve -- real pages. task type Server_Task is entry Start (S : in Server_Access); -- entry Stop; end Server_Task; type Server is new Ada.Finalization.Limited_Controlled with record Port : Natural := 0; Need_Shutdown : Boolean := False; Server : Server_Task; end record; end Util.Tests.Servers;
Update comment
Update comment
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
d70d8f7f70119e3c00a0493ad7ed7b831d79f30c
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_HEADER, N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK | N_IMAGE => Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a HTML tag start node to the document. procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Declare the Get_Tag_Name function
Declare the Get_Tag_Name function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
987b59444a21c8e8b36bbbc745667311ea722a67
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; 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 <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;
Document the streams framework
Document the streams framework
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
64743146e64f78ada7fb0f71964eaf25d0fab92e
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; type Driver_Initialize_Access is not null access procedure; procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Fix some compilation warnings
Fix some compilation warnings
Ada
apache-2.0
stcarrez/ada-ado
55ff6d45dd690a2b680e2cf41000cffd038e7709
src/asf-navigations-mappers.ads
src/asf-navigations-mappers.ads
----------------------------------------------------------------------- -- asf-navigations-mappers -- Read XML navigation files -- 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 Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with EL.Contexts; -- The <b>ASF.Navigations.Reader</b> package defines an XML mapper that can be used -- to read the XML navigation files. package ASF.Navigations.Mappers is type Navigation_Case_Fields is (FROM_VIEW_ID, OUTCOME, ACTION, TO_VIEW, REDIRECT, CONDITION, CONTENT, CONTENT_TYPE, NAVIGATION_CASE, NAVIGATION_RULE); -- ------------------------------ -- Navigation Config Reader -- ------------------------------ -- When reading and parsing the XML navigation file, the <b>Nav_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of the navigation case element is reached, -- the new navigation case is inserted in the navigation handler. type Nav_Config is limited record Outcome : Util.Beans.Objects.Object; Action : Util.Beans.Objects.Object; To_View : Util.Beans.Objects.Object; From_View : Util.Beans.Objects.Object; Redirect : Boolean := False; Condition : Util.Beans.Objects.Object; Content : Util.Beans.Objects.Object; Content_Type : Util.Beans.Objects.Object; Context : EL.Contexts.ELContext_Access; Handler : Navigation_Handler_Access; end record; type Nav_Config_Access is access all Nav_Config; -- Save in the navigation config object the value associated with the given field. -- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule -- that was collected in the navigation handler. procedure Set_Member (N : in out Nav_Config; Field : in Navigation_Case_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the navigation rules. generic Mapper : in out Util.Serialize.Mappers.Processing; Handler : in Navigation_Handler_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Nav_Config; end Reader_Config; private -- Reset the navigation config before parsing a new rule. procedure Reset (N : in out Nav_Config); package Navigation_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Nav_Config, Element_Type_Access => Nav_Config_Access, Fields => Navigation_Case_Fields, Set_Member => Set_Member); end ASF.Navigations.Mappers;
----------------------------------------------------------------------- -- asf-navigations-mappers -- Read XML navigation files -- Copyright (C) 2010, 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with EL.Contexts; -- The <b>ASF.Navigations.Reader</b> package defines an XML mapper that can be used -- to read the XML navigation files. package ASF.Navigations.Mappers is type Navigation_Case_Fields is (FROM_VIEW_ID, OUTCOME, ACTION, TO_VIEW, REDIRECT, CONDITION, CONTENT, CONTENT_TYPE, NAVIGATION_CASE, NAVIGATION_RULE, STATUS); -- ------------------------------ -- Navigation Config Reader -- ------------------------------ -- When reading and parsing the XML navigation file, the <b>Nav_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of the navigation case element is reached, -- the new navigation case is inserted in the navigation handler. type Nav_Config is limited record Outcome : Util.Beans.Objects.Object; Action : Util.Beans.Objects.Object; To_View : Util.Beans.Objects.Object; From_View : Util.Beans.Objects.Object; Redirect : Boolean := False; Condition : Util.Beans.Objects.Object; Content : Util.Beans.Objects.Object; Content_Type : Util.Beans.Objects.Object; Status : Natural := 0; Context : EL.Contexts.ELContext_Access; Handler : Navigation_Handler_Access; end record; type Nav_Config_Access is access all Nav_Config; -- Save in the navigation config object the value associated with the given field. -- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule -- that was collected in the navigation handler. procedure Set_Member (N : in out Nav_Config; Field : in Navigation_Case_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the navigation rules. generic Mapper : in out Util.Serialize.Mappers.Processing; Handler : in Navigation_Handler_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Nav_Config; end Reader_Config; private -- Reset the navigation config before parsing a new rule. procedure Reset (N : in out Nav_Config); package Navigation_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Nav_Config, Element_Type_Access => Nav_Config_Access, Fields => Navigation_Case_Fields, Set_Member => Set_Member); end ASF.Navigations.Mappers;
Add a STATUS enum member to the Navigation_Case_Fields enum
Add a STATUS enum member to the Navigation_Case_Fields enum
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9d2b4603766d7de296eb58b0f2a9a3ebef1aa692
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Fixed; with Orka.Logging; with Orka.OS; with Orka.Terminals; with EGL.Objects.Configs; with EGL.Objects.Surfaces; with Wayland.Protocols.Client.AWT; package body Orka.Contexts.EGL.Wayland.AWT is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State; use Standard.AWT.Monitors; begin Messages.Log (Debug, "Window visible on monitor"); Messages.Log (Debug, " name: " & (+State.Name)); Messages.Log (Debug, " offset: " & Trim (State.X'Image) & ", " & Trim (State.Y'Image)); Messages.Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Messages.Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh)); end Print_Monitor; ---------------------------------------------------------------------------- overriding function Width (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Width; end Width; overriding function Height (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Height; end Height; ---------------------------------------------------------------------------- overriding procedure On_Move (Object : in out AWT_Window; Monitor : Standard.AWT.Monitors.Monitor'Class; Presence : Standard.AWT.Windows.Monitor_Presence) is use all type Standard.AWT.Windows.Monitor_Presence; use Standard.AWT.Monitors; begin case Presence is when Entered => Print_Monitor (Monitor); when Left => Messages.Log (Debug, "Window no longer visible on monitor"); Messages.Log (Debug, " name: " & (+Monitor.State.Name)); end case; end On_Move; ---------------------------------------------------------------------------- overriding procedure Make_Current (Object : AWT_Context; Window : in out Orka.Windows.Window'Class) is begin if Window not in AWT_Window'Class then raise Constraint_Error; end if; AWT_Window (Window).Make_Current (Object.Context); end Make_Current; overriding function Create_Context (Version : Orka.Contexts.Context_Version; Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is begin if not Standard.AWT.Is_Initialized then Standard.AWT.Initialize; end if; return Create_Context (Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all), Version, Flags); end Create_Context; overriding function Create_Window (Context : Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return AWT_Window is package EGL_Configs renames Standard.EGL.Objects.Configs; package EGL_Surfaces renames Standard.EGL.Objects.Surfaces; use all type Standard.EGL.Objects.Contexts.Buffer_Kind; use type EGL_Configs.Config; package SF renames Ada.Strings.Fixed; Object : AWT_Context renames AWT_Context (Context); begin return Result : AWT_Window do declare Configs : constant EGL_Configs.Config_Array := EGL_Configs.Get_Configs (Object.Context.Display, 8, 8, 8, (if Transparent then 8 else 0), 24, 8, EGL_Configs.Sample_Size (Samples)); Used_Config : EGL_Configs.Config renames Configs (Configs'First); begin Messages.Log (Debug, "EGL configs: (" & Trim (Natural'Image (Configs'Length)) & ")"); Messages.Log (Debug, " Re Gr Bl Al De St Ms"); Messages.Log (Debug, " --------------------"); for Config of Configs loop declare State : constant EGL_Configs.Config_State := Config.State; begin Messages.Log (Debug, " - " & SF.Tail (Trim (State.Red'Image), 2) & " " & SF.Tail (Trim (State.Green'Image), 2) & " " & SF.Tail (Trim (State.Blue'Image), 2) & " " & SF.Tail (Trim (State.Alpha'Image), 2) & " " & SF.Tail (Trim (State.Depth'Image), 2) & " " & SF.Tail (Trim (State.Stencil'Image), 2) & " " & SF.Tail (Trim (State.Samples'Image), 2) & (if Config = Used_Config then " (used)" else "")); end; end loop; Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => True); Result.Create_Window ("", Title, Width, Height, Visible => Visible, Resizable => Resizable, Decorated => True, Transparent => Transparent); Result.Make_Current (Object.Context); pragma Assert (Object.Context.Buffer = Back); Messages.Log (Debug, "Created AWT window"); Messages.Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no")); Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no")); Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no")); end; end return; end Create_Window; end Orka.Contexts.EGL.Wayland.AWT;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Fixed; with Orka.Logging; with Orka.Terminals; with EGL.Objects.Configs; with EGL.Objects.Surfaces; with Wayland.Protocols.Client.AWT; package body Orka.Contexts.EGL.Wayland.AWT is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Window_System); procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State; use Standard.AWT.Monitors; begin Messages.Log (Debug, "Window visible on monitor"); Messages.Log (Debug, " name: " & (+State.Name)); Messages.Log (Debug, " offset: " & Trim (State.X'Image) & ", " & Trim (State.Y'Image)); Messages.Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Messages.Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh)); end Print_Monitor; ---------------------------------------------------------------------------- overriding function Width (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Width; end Width; overriding function Height (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Height; end Height; ---------------------------------------------------------------------------- overriding procedure On_Move (Object : in out AWT_Window; Monitor : Standard.AWT.Monitors.Monitor'Class; Presence : Standard.AWT.Windows.Monitor_Presence) is use all type Standard.AWT.Windows.Monitor_Presence; use Standard.AWT.Monitors; begin case Presence is when Entered => Print_Monitor (Monitor); when Left => Messages.Log (Debug, "Window no longer visible on monitor"); Messages.Log (Debug, " name: " & (+Monitor.State.Name)); end case; end On_Move; ---------------------------------------------------------------------------- overriding procedure Make_Current (Object : AWT_Context; Window : in out Orka.Windows.Window'Class) is begin if Window not in AWT_Window'Class then raise Constraint_Error; end if; AWT_Window (Window).Make_Current (Object.Context); end Make_Current; overriding function Create_Context (Version : Orka.Contexts.Context_Version; Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is begin if not Standard.AWT.Is_Initialized then Standard.AWT.Initialize; end if; return Create_Context (Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all), Version, Flags); end Create_Context; overriding function Create_Window (Context : Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return AWT_Window is package EGL_Configs renames Standard.EGL.Objects.Configs; package EGL_Surfaces renames Standard.EGL.Objects.Surfaces; use all type Standard.EGL.Objects.Contexts.Buffer_Kind; use type EGL_Configs.Config; package SF renames Ada.Strings.Fixed; Object : AWT_Context renames AWT_Context (Context); begin return Result : AWT_Window do declare Configs : constant EGL_Configs.Config_Array := EGL_Configs.Get_Configs (Object.Context.Display, 8, 8, 8, (if Transparent then 8 else 0), 24, 8, EGL_Configs.Sample_Size (Samples)); Used_Config : EGL_Configs.Config renames Configs (Configs'First); begin Messages.Log (Debug, "EGL configs: (" & Trim (Natural'Image (Configs'Length)) & ")"); Messages.Log (Debug, " Re Gr Bl Al De St Ms"); Messages.Log (Debug, " --------------------"); for Config of Configs loop declare State : constant EGL_Configs.Config_State := Config.State; begin Messages.Log (Debug, " - " & SF.Tail (Trim (State.Red'Image), 2) & " " & SF.Tail (Trim (State.Green'Image), 2) & " " & SF.Tail (Trim (State.Blue'Image), 2) & " " & SF.Tail (Trim (State.Alpha'Image), 2) & " " & SF.Tail (Trim (State.Depth'Image), 2) & " " & SF.Tail (Trim (State.Stencil'Image), 2) & " " & SF.Tail (Trim (State.Samples'Image), 2) & (if Config = Used_Config then " (used)" else "")); end; end loop; Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => True); Result.Create_Window ("", Title, Width, Height, Visible => Visible, Resizable => Resizable, Decorated => True, Transparent => Transparent); Result.Make_Current (Object.Context); pragma Assert (Object.Context.Buffer = Back); Messages.Log (Debug, "Created AWT window"); Messages.Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Messages.Log (Debug, " visible: " & (if Visible then "yes" else "no")); Messages.Log (Debug, " resizable: " & (if Resizable then "yes" else "no")); Messages.Log (Debug, " transparent: " & (if Transparent then "yes" else "no")); end; end return; end Create_Window; end Orka.Contexts.EGL.Wayland.AWT;
Remove with'ing unused unit
wayland: Remove with'ing unused unit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f303ae751b699b6287c05ca6fe8573dc550d0ae8
src/sys/streams/util-streams.adb
src/sys/streams/util-streams.adb
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Streams is use Ada.Streams; -- ------------------------------ -- Copy the input stream to the output stream until the end of the input stream -- is reached. -- ------------------------------ procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class) is Buffer : Stream_Element_Array (0 .. 4_096); Last : Stream_Element_Offset; begin loop From.Read (Buffer, Last); if Last > Buffer'First then Into.Write (Buffer (Buffer'First .. Last)); end if; exit when Last < Buffer'Last; end loop; end Copy; -- ------------------------------ -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. -- ------------------------------ procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String) is Pos : Positive := Into'First; begin for I in From'Range loop Into (Pos) := Character'Val (From (I)); Pos := Pos + 1; end loop; end Copy; -- ------------------------------ -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. -- ------------------------------ procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; begin for I in From'Range loop Into (Pos) := Character'Pos (From (I)); Pos := Pos + 1; end loop; end Copy; end Util.Streams;
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2011, 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 Interfaces; package body Util.Streams is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Copy the input stream to the output stream until the end of the input stream -- is reached. -- ------------------------------ procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class) is Buffer : Stream_Element_Array (0 .. 4_096); Last : Stream_Element_Offset; begin loop From.Read (Buffer, Last); if Last > Buffer'First then Into.Write (Buffer (Buffer'First .. Last)); end if; exit when Last < Buffer'Last; end loop; end Copy; -- ------------------------------ -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. -- ------------------------------ procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String) is Pos : Positive := Into'First; begin for I in From'Range loop Into (Pos) := Character'Val (From (I)); Pos := Pos + 1; end loop; end Copy; -- ------------------------------ -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. -- ------------------------------ procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; begin for I in From'Range loop Into (Pos) := Character'Pos (From (I)); Pos := Pos + 1; end loop; end Copy; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Output_Stream'Class; Item : in Character) is Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1) := (1 => Ada.Streams.Stream_Element (Character'Pos (Item))); begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; Buf : Ada.Streams.Stream_Element_Array (1 .. 4); begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Buf (1) := Ada.Streams.Stream_Element (Val); Stream.Write (Buf (1 .. 1)); elsif Val <= 16#07FF# then Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6)); Buf (2) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 2)); elsif Val <= 16#0FFFF# then Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (3) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 3)); else Val := Val and 16#1FFFFF#; Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18)); Val := Val and 16#3FFFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (4) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 4)); end if; end Write_Wide; procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_String) is begin for C of Item loop Stream.Write_Wide (C); end loop; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Output_Stream'Class; Item : in String) is Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last)); for Buf'Address use Item'Address; begin Stream.Write (Buf); end Write; end Util.Streams;
Implement Write and Write_Wide with UTF-8 convertion
Implement Write and Write_Wide with UTF-8 convertion
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2eea3fa24b3a728fdd476ff23cb918b33895d727
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 := ':'; 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; type File_Type is new Integer; -- 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 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; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "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; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "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; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, 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; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 := ':'; 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; type File_Type is new Integer; -- 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 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; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "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; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "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; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, 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; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- 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; pragma Import (C, Sys_Rename, "rename"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
Declare the Sys_Rename operation
Declare the Sys_Rename operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
73f54de63be94ff656774ccf0ffb4993ffb885d4
src/sqlite/ado-schemas-sqlite.adb
src/sqlite/ado-schemas-sqlite.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- 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 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_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; -- ------------------------------ -- 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); Col.Col_Type := String_To_Type (Util.Strings.Transforms.To_Lower_Case (To_String (Value))); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; 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_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; -- ------------------------------ -- 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); Col.Col_Type := String_To_Type (Util.Strings.Transforms.To_Lower_Case (To_String (Value))); 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;
Set the Is_Primary column attribute if the column is a primary key
Set the Is_Primary column attribute if the column is a primary key
Ada
apache-2.0
stcarrez/ada-ado
b851e9b0c94fdd074f0e7ae428550c604c4c1ad2
regtests/util-log-tests.ads
regtests/util-log-tests.ads
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2015, 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.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); procedure Test_Console_Appender (T : in out Test); procedure Test_Missing_Config (T : in out Test); procedure Test_Log_Traceback (T : in out Test); -- Test file appender with different modes. procedure Test_File_Appender_Modes (T : in out Test); end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2015, 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.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_Debug (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); procedure Test_Console_Appender (T : in out Test); procedure Test_Missing_Config (T : in out Test); procedure Test_Log_Traceback (T : in out Test); -- Test file appender with different modes. procedure Test_File_Appender_Modes (T : in out Test); end Util.Log.Tests;
Declare the Test_Debug procedure
Declare the Test_Debug procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ebd8ddf9d549713a85697da45edf8344a27d3db2
regtests/util-log-tests.ads
regtests/util-log-tests.ads
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); -- Test file appender with different modes. procedure Test_File_Appender_Modes (T : in out Test); end Util.Log.Tests;
Declare the Test_File_Appender_Modes procedure
Declare the Test_File_Appender_Modes procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util