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
4865b2e4db15a526dce573f34dfe40dfb407e245
test/src/wavefiles_test.adb
test/src/wavefiles_test.adb
------------------------------------------------------------------------------- -- -- WAVEFILES -- -- Test application -- -- The MIT License (MIT) -- -- Copyright (c) 2015 Gustavo A. Hoffmann -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and / -- or sell copies of the Software, and to permit persons to whom the Software -- is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. ------------------------------------------------------------------------------- with Ada.Command_Line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with Wavefiles; with Wavefiles.Read; with Wavefiles.Write; with Wavefiles.PCM_Buffers.IO; with Wavefiles.PCM_Buffers.Operators; with RIFF; procedure Wavefiles_Test is Command_Line_OK : Boolean := False; Fixed_Depth : constant Positive := 32; pragma Warnings (Off, "declared high bound of type"); type Fixed_Long is delta 1.0 / 2.0 ** (Fixed_Depth - 1) range -1.0 .. 1.0 with Size => Fixed_Depth; pragma Warnings (On, "declared high bound of type"); Channels : constant Positive := 6; Samples : constant Positive := 2048; package PCM_Buf is new Wavefiles.PCM_Buffers (Samples, Fixed_Long); package PCM_IO is new PCM_Buf.IO; package PCM_Op is new PCM_Buf.Operators; package Wav_Read renames Wavefiles.Read; package Wav_Write renames Wavefiles.Write; Verbose : constant Boolean := False; procedure Display_Info_File (File_In : String); procedure Copy_File (File_In : String; File_Out : String); procedure Compare_Files (File_Ref : String; File_DUT : String); procedure Diff_Files (File_Ref : String; File_DUT : String; File_Diff : String); procedure Mix_Files (File_Ref : String; File_DUT : String; File_Mix : String); procedure Print_Usage; -- Nested procedures procedure Display_Info_File (File_In : String) is WF_In : Wavefiles.Wavefile; begin Wav_Read.Open (WF_In, File_In); Wav_Read.Display_Info (WF_In); Wav_Read.Close (WF_In); end Display_Info_File; procedure Copy_File (File_In : String; File_Out : String) is WF_In : Wavefiles.Wavefile; WF_Out : Wavefiles.Wavefile; PCM : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF : Boolean; Frame : Integer := 0; begin Wav_Read.Open (WF_In, File_In); Wave_Format := Wavefiles.Get_Wave_Format (WF_In); Wav_Write.Open (WF_Out, File_Out, Wave_Format); if Verbose then Put_Line ("Input File:"); Wav_Read.Display_Info (WF_In); Put_Line ("Output File:"); Wav_Read.Display_Info (WF_Out); end if; loop Frame := Frame + 1; if Verbose then Put ("[" & Integer'Image (Frame) & "]"); end if; PCM_IO.Read (WF_In, PCM, EOF); PCM_IO.Write (WF_Out, PCM); exit when EOF; end loop; Wav_Read.Close (WF_In); Wav_Write.Close (WF_Out); end Copy_File; procedure Compare_Files (File_Ref : String; File_DUT : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; Diff_Frames : Natural := 0; Frame : Integer := 0; begin Wave_Format.Set_Default; Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); loop Frame := Frame + 1; PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); if not PCM_Buf."=" (PCM_Ref, PCM_DUT) then Diff_Frames := Diff_Frames + 1; Put_Line ("Difference found at frame " & Integer'Image (Frame)); end if; exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); if Diff_Frames > 0 then Put_Line ("Differences have been found in " & Natural'Image (Diff_Frames) & " frames"); else Put_Line ("No differences have been found"); end if; end Compare_Files; procedure Diff_Files (File_Ref : String; File_DUT : String; File_Diff : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; WF_Diff : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); PCM_Diff : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; begin RIFF.Set_Default (Wave_Format); Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); Wav_Write.Open (WF_Diff, File_Diff, Wave_Format); loop PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); PCM_Diff := PCM_Op."-" (PCM_Ref, PCM_DUT); PCM_IO.Write (WF_Diff, PCM_Diff); exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); Wav_Write.Close (WF_Diff); end Diff_Files; procedure Mix_Files (File_Ref : String; File_DUT : String; File_Mix : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; WF_Mix : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); PCM_Mix : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; begin RIFF.Set_Default (Wave_Format); Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); Wav_Write.Open (WF_Mix, File_Mix, Wave_Format); loop PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); PCM_Mix := PCM_Op."+" (PCM_Ref, PCM_DUT); PCM_IO.Write (WF_Mix, PCM_Mix); exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); Wav_Write.Close (WF_Mix); end Mix_Files; procedure Print_Usage is begin Put_Line ("Usage: " & Command_Name & " <command>"); New_Line; Put_Line (" info <input_wavefile>"); Put_Line (" copy <input_wavefile> <output_wavefile>"); Put_Line (" compare <ref_wavefile> <dut_wavefile>"); Put_Line (" diff <ref_wavefile> <dut_wavefile> " & "<diff_wavefile>"); Put_Line (" mix <wavefile_1> <wavefile_1> " & "<mix_wavefile>"); end Print_Usage; begin if Argument_Count >= 1 then if Argument (1) = "info" and then Argument_Count = 2 then Command_Line_OK := True; Put_Line ("Information from: " & Argument (2)); Display_Info_File (Argument (2)); elsif Argument (1) = "copy" and then Argument_Count = 3 then Command_Line_OK := True; Put_Line ("Copying from: " & Argument (2)); Put_Line ("Copying to: " & Argument (3)); Copy_File (Argument (2), Argument (3)); elsif Argument (1) = "compare" and then Argument_Count = 3 then Command_Line_OK := True; Put_Line ("Reference: " & Argument (2)); Put_Line ("DUT: " & Argument (3)); Compare_Files (Argument (2), Argument (3)); elsif Argument (1) = "diff" and then Argument_Count = 4 then Command_Line_OK := True; Put_Line ("Reference: " & Argument (2)); Put_Line ("DUT: " & Argument (3)); Put_Line ("Diff: " & Argument (4)); Diff_Files (Argument (2), Argument (3), Argument (4)); elsif Argument (1) = "mix" and then Argument_Count = 4 then Command_Line_OK := True; Put_Line ("Wavefile #1: " & Argument (2)); Put_Line ("Wavefile #2: " & Argument (3)); Put_Line ("Mix file: " & Argument (4)); Mix_Files (Argument (2), Argument (3), Argument (4)); end if; end if; if not Command_Line_OK then Print_Usage; end if; end Wavefiles_Test;
------------------------------------------------------------------------------- -- -- WAVEFILES -- -- Test application -- -- The MIT License (MIT) -- -- Copyright (c) 2015 Gustavo A. Hoffmann -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and / -- or sell copies of the Software, and to permit persons to whom the Software -- is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. ------------------------------------------------------------------------------- with Ada.Command_Line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with Wavefiles; with Wavefiles.Read; with Wavefiles.Write; with Wavefiles.PCM_Buffers.IO; with Wavefiles.PCM_Buffers.Operators; with RIFF; procedure Wavefiles_Test is Command_Line_OK : Boolean := False; package Wave_Test is procedure Display_Info_File (File_In : String); procedure Copy_File (File_In : String; File_Out : String); procedure Compare_Files (File_Ref : String; File_DUT : String); procedure Diff_Files (File_Ref : String; File_DUT : String; File_Diff : String); procedure Mix_Files (File_Ref : String; File_DUT : String; File_Mix : String); end Wave_Test; procedure Print_Usage; -- Nested package & procedures package body Wave_Test is Fixed_Depth : constant Positive := 32; pragma Warnings (Off, "declared high bound of type"); type Fixed_Long is delta 1.0 / 2.0 ** (Fixed_Depth - 1) range -1.0 .. 1.0 with Size => Fixed_Depth; pragma Warnings (On, "declared high bound of type"); Channels : constant Positive := 6; Samples : constant Positive := 2048; package PCM_Buf is new Wavefiles.PCM_Buffers (Samples, Fixed_Long); package PCM_IO is new PCM_Buf.IO; package PCM_Op is new PCM_Buf.Operators; package Wav_Read renames Wavefiles.Read; package Wav_Write renames Wavefiles.Write; Verbose : constant Boolean := False; procedure Display_Info_File (File_In : String) is WF_In : Wavefiles.Wavefile; begin Wav_Read.Open (WF_In, File_In); Wav_Read.Display_Info (WF_In); Wav_Read.Close (WF_In); end Display_Info_File; procedure Copy_File (File_In : String; File_Out : String) is WF_In : Wavefiles.Wavefile; WF_Out : Wavefiles.Wavefile; PCM : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF : Boolean; Frame : Integer := 0; begin Wav_Read.Open (WF_In, File_In); Wave_Format := Wavefiles.Get_Wave_Format (WF_In); Wav_Write.Open (WF_Out, File_Out, Wave_Format); if Verbose then Put_Line ("Input File:"); Wav_Read.Display_Info (WF_In); Put_Line ("Output File:"); Wav_Read.Display_Info (WF_Out); end if; loop Frame := Frame + 1; if Verbose then Put ("[" & Integer'Image (Frame) & "]"); end if; PCM_IO.Read (WF_In, PCM, EOF); PCM_IO.Write (WF_Out, PCM); exit when EOF; end loop; Wav_Read.Close (WF_In); Wav_Write.Close (WF_Out); end Copy_File; procedure Compare_Files (File_Ref : String; File_DUT : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; Diff_Frames : Natural := 0; Frame : Integer := 0; begin Wave_Format.Set_Default; Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); loop Frame := Frame + 1; PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); if not PCM_Buf."=" (PCM_Ref, PCM_DUT) then Diff_Frames := Diff_Frames + 1; Put_Line ("Difference found at frame " & Integer'Image (Frame)); end if; exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); if Diff_Frames > 0 then Put_Line ("Differences have been found in " & Natural'Image (Diff_Frames) & " frames"); else Put_Line ("No differences have been found"); end if; end Compare_Files; procedure Diff_Files (File_Ref : String; File_DUT : String; File_Diff : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; WF_Diff : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); PCM_Diff : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; begin RIFF.Set_Default (Wave_Format); Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); Wav_Write.Open (WF_Diff, File_Diff, Wave_Format); loop PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); PCM_Diff := PCM_Op."-" (PCM_Ref, PCM_DUT); PCM_IO.Write (WF_Diff, PCM_Diff); exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); Wav_Write.Close (WF_Diff); end Diff_Files; procedure Mix_Files (File_Ref : String; File_DUT : String; File_Mix : String) is WF_Ref : Wavefiles.Wavefile; WF_DUT : Wavefiles.Wavefile; WF_Mix : Wavefiles.Wavefile; PCM_Ref : PCM_Buf.PCM_Buffer (Channels); PCM_DUT : PCM_Buf.PCM_Buffer (Channels); PCM_Mix : PCM_Buf.PCM_Buffer (Channels); Wave_Format : RIFF.Wave_Format_Extensible; EOF_Ref, EOF_DUT : Boolean; begin RIFF.Set_Default (Wave_Format); Wav_Read.Open (WF_Ref, File_Ref); Wav_Read.Open (WF_DUT, File_DUT); Wav_Write.Open (WF_Mix, File_Mix, Wave_Format); loop PCM_IO.Read (WF_Ref, PCM_Ref, EOF_Ref); PCM_IO.Read (WF_DUT, PCM_DUT, EOF_DUT); PCM_Mix := PCM_Op."+" (PCM_Ref, PCM_DUT); PCM_IO.Write (WF_Mix, PCM_Mix); exit when EOF_Ref or EOF_DUT; end loop; Wav_Read.Close (WF_Ref); Wav_Read.Close (WF_DUT); Wav_Write.Close (WF_Mix); end Mix_Files; end Wave_Test; procedure Print_Usage is begin Put_Line ("Usage: " & Command_Name & " <command>"); New_Line; Put_Line (" info <input_wavefile>"); Put_Line (" copy <input_wavefile> <output_wavefile>"); Put_Line (" compare <ref_wavefile> <dut_wavefile>"); Put_Line (" diff <ref_wavefile> <dut_wavefile> " & "<diff_wavefile>"); Put_Line (" mix <wavefile_1> <wavefile_1> " & "<mix_wavefile>"); end Print_Usage; begin if Argument_Count >= 1 then if Argument (1) = "info" and then Argument_Count = 2 then Command_Line_OK := True; Put_Line ("Information from: " & Argument (2)); Wave_Test.Display_Info_File (Argument (2)); elsif Argument (1) = "copy" and then Argument_Count = 3 then Command_Line_OK := True; Put_Line ("Copying from: " & Argument (2)); Put_Line ("Copying to: " & Argument (3)); Wave_Test.Copy_File (Argument (2), Argument (3)); elsif Argument (1) = "compare" and then Argument_Count = 3 then Command_Line_OK := True; Put_Line ("Reference: " & Argument (2)); Put_Line ("DUT: " & Argument (3)); Wave_Test.Compare_Files (Argument (2), Argument (3)); elsif Argument (1) = "diff" and then Argument_Count = 4 then Command_Line_OK := True; Put_Line ("Reference: " & Argument (2)); Put_Line ("DUT: " & Argument (3)); Put_Line ("Diff: " & Argument (4)); Wave_Test.Diff_Files (Argument (2), Argument (3), Argument (4)); elsif Argument (1) = "mix" and then Argument_Count = 4 then Command_Line_OK := True; Put_Line ("Wavefile #1: " & Argument (2)); Put_Line ("Wavefile #2: " & Argument (3)); Put_Line ("Mix file: " & Argument (4)); Wave_Test.Mix_Files (Argument (2), Argument (3), Argument (4)); end if; end if; if not Command_Line_OK then Print_Usage; end if; end Wavefiles_Test;
Test application: added nested package (Wave_Test)
Test application: added nested package (Wave_Test)
Ada
mit
gusthoff/wavefiles
83f425088dc46c21148f6692f346de58499e1875
testcases/fruit2/fruit2.adb
testcases/fruit2/fruit2.adb
with AdaBase; with Connect; with Ada.Text_IO; procedure Fruit2 is package CON renames Connect; package TIO renames Ada.Text_IO; numrows : AdaBase.AffectedRows; -- Intentionally broken UPDATE command (calories misspelling) cmd : constant String := "UPDATE fruits set caloriesx = 14 " & "WHERE fruit = 'strawberry'"; begin declare begin CON.connect_database; CON.DR.set_trait_error_mode (trait => AdaBase.raise_exception); exception when others => TIO.Put_Line ("database connect failed."); return; end; TIO.Put_Line ("SQL: " & cmd); declare begin numrows := CON.DR.execute (sql => cmd); TIO.Put_Line ("Result: Updated" & numrows'Img & " rows"); CON.DR.rollback; exception when others => TIO.Put_Line ("Error!"); TIO.Put_Line ("Driver message: " & CON.DR.last_driver_message); TIO.Put_Line (" Driver code: " & CON.DR.last_driver_code'Img); TIO.Put_Line (" SQL State: " & CON.DR.last_sql_state); end; CON.DR.disconnect; end Fruit2;
with AdaBase; with Connect; with Ada.Text_IO; procedure Fruit2 is package CON renames Connect; package TIO renames Ada.Text_IO; numrows : AdaBase.AffectedRows; -- Intentionally broken UPDATE command (calories misspelled) cmd : constant String := "UPDATE fruits set caloriesx = 14 " & "WHERE fruit = 'strawberry'"; begin declare begin CON.connect_database; CON.DR.set_trait_error_mode (trait => AdaBase.raise_exception); exception when others => TIO.Put_Line ("database connect failed."); return; end; TIO.Put_Line ("SQL: " & cmd); declare begin numrows := CON.DR.execute (sql => cmd); TIO.Put_Line ("Result: Updated" & numrows'Img & " rows"); CON.DR.rollback; exception when others => TIO.Put_Line ("Error!"); TIO.Put_Line ("Driver message: " & CON.DR.last_driver_message); TIO.Put_Line (" Driver code: " & CON.DR.last_driver_code'Img); TIO.Put_Line (" SQL State: " & CON.DR.last_sql_state); end; CON.DR.disconnect; end Fruit2;
Fix typo in fruit2 testcase comment
Fix typo in fruit2 testcase comment
Ada
isc
jrmarino/AdaBase
65bce8bc9905a678f7098f79ce9c2c837269fcdd
src/util-encoders.ads
src/util-encoders.ads
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- 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.Streams; with Ada.Finalization; with Ada.Strings.Unbounded; with Interfaces; -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> object -- which represents a mechanism to transform a stream from one format into -- another format. package Util.Encoders is pragma Preelaborate; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Encoder; Data : in String) return String; -- Create the encoder object for the specified encoding format. function Create (Name : String) return Encoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input stream represented by <b>Data</b> into -- the output stream <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, ...). -- -- 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. procedure Transform (E : in Transformer; 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 abstract; procedure Transform (E : in Transformer; Data : in String; Result : out Ada.Strings.Unbounded.Unbounded_String) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Ada.Finalization.Limited_Controlled with record Encode : Transformer_Access := null; Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Ada.Strings.Unbounded; with Interfaces; -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> object -- which represents a mechanism to transform a stream from one format into -- another format. package Util.Encoders is pragma Preelaborate; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Encoder; Data : in String) return String; -- Create the encoder object for the specified encoding format. function Create (Name : String) return Encoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input stream represented by <b>Data</b> into -- the output stream <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, ...). -- -- 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. procedure Transform (E : in Transformer; 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 abstract; procedure Transform (E : in Transformer; Data : in String; Result : out Ada.Strings.Unbounded.Unbounded_String) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed procedure Transform (E : in Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Ada.Finalization.Limited_Controlled with record Encode : Transformer_Access := null; Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); end Util.Encoders;
Declare new Transform procedure to transform a string using the encoder and produce a stream element array
Declare new Transform procedure to transform a string using the encoder and produce a stream element array
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9ee37ef8549f3998310a91d2f00728ef2e2b5785
src/wiki-streams-builders.adb
src/wiki-streams-builders.adb
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Encode_UTF8_String; package body Wiki.Streams.Builders is use Wiki.Strings; package WBS renames Wiki.Strings.Wide_Wide_Builders; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_String) is begin WBS.Append (Stream.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_Character) is begin WBS.Append (Stream.Content, Content); end Write; -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in String) is begin for I in Content'Range loop WBS.Append (Stream.Content, Wiki.Strings.To_WChar (Content (I))); end loop; end Write_String; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wide_Wide_String)) is begin Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Output_Builder_Stream) return String is procedure Convert (Chunk : in Wide_Wide_String); Pos : Natural := 1; Result : String (1 .. 5 * Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wide_Wide_String) is begin for I in Chunk'Range loop GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I), Result => Result, Ptr => Pos); end loop; end Convert; begin Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result (1 .. Pos - 1); end To_String; end Wiki.Streams.Builders;
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Encode_UTF8_String; package body Wiki.Streams.Builders is -- use Wiki.Strings; package WBS renames Wiki.Strings.Wide_Wide_Builders; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wiki.Strings.WString) is begin WBS.Append (Stream.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wiki.Strings.WChar) is begin WBS.Append (Stream.Content, Content); end Write; -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in String) is begin for I in Content'Range loop WBS.Append (Stream.Content, Wiki.Strings.To_WChar (Content (I))); end loop; end Write_String; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wiki.Strings.WString)) is begin Strings.Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Output_Builder_Stream) return String is procedure Convert (Chunk : in Wiki.Strings.WString); Pos : Natural := 1; Result : String (1 .. 5 * Strings.Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wiki.Strings.WString) is begin for I in Chunk'Range loop GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I), Result => Result, Ptr => Pos); end loop; end Convert; begin Strings.Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result (1 .. Pos - 1); end To_String; end Wiki.Streams.Builders;
Use Wiki.Strings.WChar type
Use Wiki.Strings.WChar type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
01717f2367c7456a6a7cca089180d235465f55bb
tools/smaz.adb
tools/smaz.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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Command Line Interface for primitives in Natools.Smaz.Tools. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO.Text_Streams; with Natools.Getopt_Long; with Natools.S_Expressions.Parsers; with Natools.Smaz.Tools; procedure Smaz is package Options is type Id is (Help, Output_Ada_Dictionary); end Options; package Getopt is new Natools.Getopt_Long (Options.Id); type Callback is new Getopt.Handlers.Callback with record Display_Help : Boolean := False; Need_Dictionary : Boolean := False; Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String); overriding procedure Argument (Handler : in out Callback; Argument : in String) is null; function Getopt_Config return Getopt.Configuration; -- Build the configuration object procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); -- print the given dictionary in the given file procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type); -- Print the help text to the given file overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String) is begin case Id is when Options.Help => Handler.Display_Help := True; when Options.Output_Ada_Dictionary => Handler.Need_Dictionary := True; if Argument'Length > 0 then Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String (Argument); else Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String ("-"); end if; end case; end Option; function Getopt_Config return Getopt.Configuration is use Getopt; use Options; R : Getopt.Configuration; begin R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary); R.Add_Option ("help", 'h', No_Argument, Help); return R; end Getopt_Config; procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is begin if Filename = "-" then Print_Dictionary (Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name); elsif Filename'Length > 0 then declare File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File, Name => Filename); Print_Dictionary (File, Dictionary, Hash_Package_Name); Ada.Text_IO.Close (File); end; end if; end Print_Dictionary; procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is procedure Put_Line (Line : in String); procedure Put_Line (Line : in String) is begin Ada.Text_IO.Put_Line (Output, Line); end Put_Line; procedure Print_Dictionary_In_Ada is new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line); begin if Hash_Package_Name'Length > 0 then Print_Dictionary_In_Ada (Dictionary, Hash_Image => Hash_Package_Name & ".Hash'Access"); else Print_Dictionary_In_Ada (Dictionary); end if; end Print_Dictionary; procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type) is use Ada.Text_IO; Indent : constant String := " "; begin Put_Line (Output, "Usage:"); for Id in Options.Id loop Put (Output, Indent & Opt.Format_Names (Id)); case Id is when Options.Help => New_Line (Output); Put_Line (Output, Indent & Indent & "Display this help text"); when Options.Output_Ada_Dictionary => Put_Line (Output, "=[filename]"); Put_Line (Output, Indent & Indent & "Output the current dictionary as Ada code in the given"); Put_Line (Output, Indent & Indent & "file, or standard output if filename is ""-"""); end case; end loop; end Print_Help; Opt_Config : constant Getopt.Configuration := Getopt_Config; Handler : Callback; Input_List : Natools.Smaz.Tools.String_Lists.List; begin Process_Command_Line : begin Opt_Config.Process (Handler); exception when Getopt.Option_Error => Print_Help (Opt_Config, Ada.Text_IO.Current_Error); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end Process_Command_Line; if Handler.Display_Help then Print_Help (Opt_Config, Ada.Text_IO.Current_Output); end if; if not Handler.Need_Dictionary then return; end if; Read_Input_List : declare Input : constant access Ada.Streams.Root_Stream_Type'Class := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input); begin Parser.Next; Natools.Smaz.Tools.Read_List (Input_List, Parser); end Read_Input_List; Build_Dictionary : declare Dictionary : constant Natools.Smaz.Dictionary := Natools.Smaz.Tools.To_Dictionary (Input_List, True); Ada_Dictionary : constant String := Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary); begin if Ada_Dictionary'Length > 0 then Print_Dictionary (Ada_Dictionary, Dictionary); end if; end Build_Dictionary; end Smaz;
------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Command Line Interface for primitives in Natools.Smaz.Tools. -- ------------------------------------------------------------------------------ with Ada.Command_Line; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO.Text_Streams; with Natools.Getopt_Long; with Natools.S_Expressions.Parsers; with Natools.Smaz.Tools; with Natools.Smaz.Tools.GNAT; procedure Smaz is package Options is type Id is (Help, Output_Ada_Dictionary, Output_Hash); end Options; package Getopt is new Natools.Getopt_Long (Options.Id); type Callback is new Getopt.Handlers.Callback with record Display_Help : Boolean := False; Need_Dictionary : Boolean := False; Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String; Hash_Package : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String); overriding procedure Argument (Handler : in out Callback; Argument : in String) is null; function Getopt_Config return Getopt.Configuration; -- Build the configuration object procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); -- print the given dictionary in the given file procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type); -- Print the help text to the given file overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String) is begin case Id is when Options.Help => Handler.Display_Help := True; when Options.Output_Ada_Dictionary => Handler.Need_Dictionary := True; if Argument'Length > 0 then Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String (Argument); else Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String ("-"); end if; when Options.Output_Hash => Handler.Need_Dictionary := True; Handler.Hash_Package := Ada.Strings.Unbounded.To_Unbounded_String (Argument); end case; end Option; function Getopt_Config return Getopt.Configuration is use Getopt; use Options; R : Getopt.Configuration; begin R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary); R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash); R.Add_Option ("help", 'h', No_Argument, Help); return R; end Getopt_Config; procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is begin if Filename = "-" then Print_Dictionary (Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name); elsif Filename'Length > 0 then declare File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File, Name => Filename); Print_Dictionary (File, Dictionary, Hash_Package_Name); Ada.Text_IO.Close (File); end; end if; end Print_Dictionary; procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is procedure Put_Line (Line : in String); procedure Put_Line (Line : in String) is begin Ada.Text_IO.Put_Line (Output, Line); end Put_Line; procedure Print_Dictionary_In_Ada is new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line); begin if Hash_Package_Name'Length > 0 then Print_Dictionary_In_Ada (Dictionary, Hash_Image => Hash_Package_Name & ".Hash'Access"); else Print_Dictionary_In_Ada (Dictionary); end if; end Print_Dictionary; procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type) is use Ada.Text_IO; Indent : constant String := " "; begin Put_Line (Output, "Usage:"); for Id in Options.Id loop Put (Output, Indent & Opt.Format_Names (Id)); case Id is when Options.Help => New_Line (Output); Put_Line (Output, Indent & Indent & "Display this help text"); when Options.Output_Ada_Dictionary => Put_Line (Output, "=[filename]"); Put_Line (Output, Indent & Indent & "Output the current dictionary as Ada code in the given"); Put_Line (Output, Indent & Indent & "file, or standard output if filename is ""-"""); when Options.Output_Hash => Put_Line (Output, " <Hash Package Name>"); Put_Line (Output, Indent & Indent & "Build a package with a perfect hash function for the"); Put_Line (Output, Indent & Indent & "current dictionary."); end case; end loop; end Print_Help; Opt_Config : constant Getopt.Configuration := Getopt_Config; Handler : Callback; Input_List : Natools.Smaz.Tools.String_Lists.List; begin Process_Command_Line : begin Opt_Config.Process (Handler); exception when Getopt.Option_Error => Print_Help (Opt_Config, Ada.Text_IO.Current_Error); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end Process_Command_Line; if Handler.Display_Help then Print_Help (Opt_Config, Ada.Text_IO.Current_Output); end if; if not Handler.Need_Dictionary then return; end if; Read_Input_List : declare Input : constant access Ada.Streams.Root_Stream_Type'Class := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input); begin Parser.Next; Natools.Smaz.Tools.Read_List (Input_List, Parser); end Read_Input_List; Build_Dictionary : declare Dictionary : constant Natools.Smaz.Dictionary := Natools.Smaz.Tools.To_Dictionary (Input_List, True); Ada_Dictionary : constant String := Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary); Hash_Package : constant String := Ada.Strings.Unbounded.To_String (Handler.Hash_Package); begin if Ada_Dictionary'Length > 0 then Print_Dictionary (Ada_Dictionary, Dictionary, Hash_Package); end if; if Hash_Package'Length > 0 then Natools.Smaz.Tools.GNAT.Build_Perfect_Hash (Input_List, Hash_Package); end if; end Build_Dictionary; end Smaz;
add support for hash function generation
tools/smaz: add support for hash function generation
Ada
isc
faelys/natools
78f83188d46bebef85414889a66e0b1c1bc7bf51
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.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the PID into a string. -- ------------------------------ function Pid (Value : in MAT.Types.Target_Process_Ref) return String is begin return Util.Strings.Image (Natural (Value)); end Pid; -- ------------------------------ -- 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 (Sec)) & 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 an event range description. -- ------------------------------ function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String is use type MAT.Events.Event_Id_Type; Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id); begin if First.Id = Last.Id then return Id1 (Id1'First + 1 .. Id1'Last); else return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last); end if; end Event; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; 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.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size); end if; when MAT.Events.MSG_BEGIN => return "begin"; when MAT.Events.MSG_END => return "end"; when MAT.Events.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Target_Event_Type; begin Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.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.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Target_Event_Type; begin Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.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.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.MSG_BEGIN => return "Begin event"; when MAT.Events.MSG_END => return "End event"; when MAT.Events.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.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the PID into a string. -- ------------------------------ function Pid (Value : in MAT.Types.Target_Process_Ref) return String is begin return Util.Strings.Image (Natural (Value)); end Pid; -- ------------------------------ -- 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 memory growth size into a string. -- ------------------------------ function Size (Alloced : in MAT.Types.Target_Size; Freed : in MAT.Types.Target_Size) return String is use type MAT.Types.Target_Size; begin if Alloced > Freed then return Size (Alloced - Freed); elsif Alloced < Freed then return "-" & Size (Freed - Alloced); else return "=" & Size (Alloced); 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 (Sec)) & 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 an event range description. -- ------------------------------ function Event (First : in MAT.Events.Target_Event_Type; Last : in MAT.Events.Target_Event_Type) return String is use type MAT.Events.Event_Id_Type; Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id); begin if First.Id = Last.Id then return Id1 (Id1'First + 1 .. Id1'Last); else return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last); end if; end Event; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; 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.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size); end if; when MAT.Events.MSG_BEGIN => return "begin"; when MAT.Events.MSG_END => return "end"; when MAT.Events.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Target_Event_Type; begin Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.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.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Target_Event_Type; begin Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.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.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Tools.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Target_Event_Type; Related : in MAT.Events.Tools.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.MSG_BEGIN => return "Begin event"; when MAT.Events.MSG_END => return "End event"; when MAT.Events.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Implement the Size function to format a memory growth (alloced/freed)
Implement the Size function to format a memory growth (alloced/freed)
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1fef6d3ed5ef1fb7dbd4f8596ac52db511197957
src/util-strings.ads
src/util-strings.ads
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Hashed_Sets; private with Util.Concurrent.Counters; package Util.Strings is pragma Preelaborate; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the pattern in the string. function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural; -- Returns True if the source string starts with the given prefix. function Starts_With (Source : in String; Prefix : in String) return Boolean; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Integer) return String; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Long_Long_Integer) return String; package String_Access_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); package String_Set is new Ada.Containers.Hashed_Sets (Element_Type => Name_Access, Hash => Hash, Equivalent_Elements => Equivalent_Keys); -- String reference type String_Ref is private; -- Create a string reference from a string. function To_String_Ref (S : in String) return String_Ref; -- Create a string reference from an unbounded string. function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref; -- Get the string function To_String (S : in String_Ref) return String; -- Get the string as an unbounded string function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String; -- Compute the hash value of the string reference. function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type; -- Returns true if left and right string references are equivalent. function Equivalent_Keys (Left, Right : in String_Ref) return Boolean; function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean; -- Returns the string length. function Length (S : in String_Ref) return Natural; private pragma Inline (To_String_Ref); pragma Inline (To_String); type String_Record (Len : Natural) is limited record Counter : Util.Concurrent.Counters.Counter; Str : String (1 .. Len); end record; type String_Record_Access is access all String_Record; type String_Ref is new Ada.Finalization.Controlled with record Str : String_Record_Access := null; end record; -- Increment the reference counter. overriding procedure Adjust (Object : in out String_Ref); -- Decrement the reference counter and free the allocated string. overriding procedure Finalize (Object : in out String_Ref); end Util.Strings;
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Hashed_Sets; private with Util.Concurrent.Counters; package Util.Strings is pragma Preelaborate; -- Constant string access type Name_Access is access constant String; -- Compute the hash value of the string. function Hash (Key : Name_Access) return Ada.Containers.Hash_Type; -- Returns true if left and right strings are equivalent. function Equivalent_Keys (Left, Right : Name_Access) return Boolean; -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural; -- Search for the first occurrence of the pattern in the string. function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural; -- Returns True if the source string starts with the given prefix. function Starts_With (Source : in String; Prefix : in String) return Boolean; -- Returns True if the source string ends with the given suffix. function Ends_With (Source : in String; Suffix : in String) return Boolean; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Integer) return String; -- Returns Integer'Image (Value) with the possible space stripped. function Image (Value : in Long_Long_Integer) return String; package String_Access_Map is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Name_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); package String_Set is new Ada.Containers.Hashed_Sets (Element_Type => Name_Access, Hash => Hash, Equivalent_Elements => Equivalent_Keys); -- String reference type String_Ref is private; -- Create a string reference from a string. function To_String_Ref (S : in String) return String_Ref; -- Create a string reference from an unbounded string. function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref; -- Get the string function To_String (S : in String_Ref) return String; -- Get the string as an unbounded string function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String; -- Compute the hash value of the string reference. function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type; -- Returns true if left and right string references are equivalent. function Equivalent_Keys (Left, Right : in String_Ref) return Boolean; function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean; -- Returns the string length. function Length (S : in String_Ref) return Natural; private pragma Inline (To_String_Ref); pragma Inline (To_String); type String_Record (Len : Natural) is limited record Counter : Util.Concurrent.Counters.Counter; Str : String (1 .. Len); end record; type String_Record_Access is access all String_Record; type String_Ref is new Ada.Finalization.Controlled with record Str : String_Record_Access := null; end record; -- Increment the reference counter. overriding procedure Adjust (Object : in out String_Ref); -- Decrement the reference counter and free the allocated string. overriding procedure Finalize (Object : in out String_Ref); end Util.Strings;
Declare the Ends_With function
Declare the Ends_With function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
de4cf5b3f08751f701f2eb9f60de20f23970a5f3
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; begin -- Generate the random sequence. for I in 0 .. Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1}", URI, Natural'Image (Response.Get_Status)); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain;" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), Expires); else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin return new Access_Token '(Len => Token'Length, Access_Id => Token); end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; begin -- Generate the random sequence. for I in 0 .. Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the application identifier. -- ------------------------------ function Get_Application_Identifier (App : in Application) return String is begin return Ada.Strings.Unbounded.To_String (App.Client_Id); end Get_Application_Identifier; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1}", URI, Natural'Image (Response.Get_Status)); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain;" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), Expires); else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin return new Access_Token '(Len => Token'Length, Access_Id => Token); end Create_Access_Token; end Security.OAuth.Clients;
Implement the new function Get_Application_Identifier
Implement the new function Get_Application_Identifier
Ada
apache-2.0
stcarrez/ada-security
cd7b62ba842e0f47059e3945cca85132bcab45cd
src/core/util-stacks.ads
src/core/util-stacks.ads
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; generic type Element_Type is private; type Element_Type_Access is access all Element_Type; package Util.Stacks is pragma Preelaborate; type Stack is limited private; -- Get access to the current stack element. function Current (Container : in Stack) return Element_Type_Access; -- Push an element on top of the stack making the new element the current one. procedure Push (Container : in out Stack); -- Pop the top element. procedure Pop (Container : in out Stack); -- Clear the stack. procedure Clear (Container : in out Stack); private type Element_Type_Array is array (Natural range <>) of aliased Element_Type; type Element_Type_Array_Access is access all Element_Type_Array; type Stack is new Ada.Finalization.Limited_Controlled with record Current : Element_Type_Access := null; Stack : Element_Type_Array_Access := null; Pos : Natural := 0; end record; -- Release the stack overriding procedure Finalize (Obj : in out Stack); end Util.Stacks;
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011, 2013, 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.Finalization; generic type Element_Type is private; type Element_Type_Access is access all Element_Type; package Util.Stacks is pragma Preelaborate; type Stack is limited private; -- Get access to the current stack element. function Current (Container : in Stack) return Element_Type_Access; -- Push an element on top of the stack making the new element the current one. procedure Push (Container : in out Stack); -- Pop the top element. procedure Pop (Container : in out Stack); -- Clear the stack. procedure Clear (Container : in out Stack); -- Returns true if the stack is empty. function Is_Empty (Container : in out Stack) return Boolean; private type Element_Type_Array is array (Natural range <>) of aliased Element_Type; type Element_Type_Array_Access is access all Element_Type_Array; type Stack is new Ada.Finalization.Limited_Controlled with record Current : Element_Type_Access := null; Stack : Element_Type_Array_Access := null; Pos : Natural := 0; end record; -- Release the stack overriding procedure Finalize (Obj : in out Stack); end Util.Stacks;
Add Is_Empty function
Add Is_Empty function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c110a16292518abfa5edd659f83b8c2a6a8d9e7c
awa/src/awa-users-services.ads
awa/src/awa-users-services.ads
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
Declare the Create_Access_Key procedure to make an access key for a user
Declare the Create_Access_Key procedure to make an access key for a user
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c8d934961f2de848c6fcd4974ec94feebaf04e3d
awa/src/awa-users-principals.ads
awa/src/awa-users-principals.ads
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Returns true if the given role is stored in the user principal. -- function Has_Role (User : in Principal; -- Role : in Security.Permissions.Role_Type) return Boolean; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; -- Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; end record; end AWA.Users.Principals;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
a3e5228143da522b0cda5d4af028105d7e45eeed
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; 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;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Named Queries == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application by using named queries. -- 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 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 Dynamo. -- -- === 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 any 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;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
e2711ed932f820e023204f3b82ed33f92681dc56
regtests/asf-servlets-tests.ads
regtests/asf-servlets-tests.ads
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Filter_Mapping (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Filter_Mapping (T : in out Test); -- Test execution of filters procedure Test_Filter_Execution (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
Declare the Test_Filter_Execution procedure
Declare the Test_Filter_Execution procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1a16881a881fe56e873e82baad0bf66754791e7a
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
stcarrez/ada-util,stcarrez/ada-util
775ef857af1cd40b11e07492d1d2ad18eeb423a0
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with AUnit; with AUnit.Test_Caller; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Util.Measures; with Util.Log; with Util.Log.Loggers; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new AUnit.Test_Caller (Test); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); Assert (T, Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin Assert (T, Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); Assert (T, False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => Assert (T, Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); Assert (T, Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); Assert (T, not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then Assert (T, Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); Assert (T, Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); Assert (T, Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; Assert (T, Result > 100, "Too few rows were deleted"); end Test_Delete_All; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access)); Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access)); Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update", Test_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access)); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with AUnit; with AUnit.Test_Caller; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Util.Measures; with Util.Log; with Util.Log.Loggers; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new AUnit.Test_Caller (Test); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin Assert (T, Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); Assert (T, False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => Assert (T, Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); Assert (T, Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); Assert (T, not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then Assert (T, Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); Assert (T, Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); Assert (T, Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; Assert (T, Result > 100, "Too few rows were deleted"); end Test_Delete_All; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access)); Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access)); Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update", Test_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access)); end Add_Tests; end ADO.Tests;
Fix compilation with GNAT 2011
Fix compilation with GNAT 2011
Ada
apache-2.0
stcarrez/ada-ado
26480b31713b9b66637612147a6adc6eb5e3dc59
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; with Util.Strings; with Util.Refs; -- 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 Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; 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; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- 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; -- Set the database name. procedure Set_Database (Controller : in out Configuration; Database : in String); -- Get the database name. function Get_Database (Controller : in Configuration) return String; -- Get the database driver name. function Get_Driver (Controller : in Configuration) return String; -- Get the database driver index. function Get_Driver (Controller : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) 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; Log_URI : Unbounded_String; Server : Unbounded_String; Port : Natural := 0; Database : 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, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Configs; with Util.Strings; with Util.Strings.Vectors; with Util.Refs; -- 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 Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; 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; -- Create the database and initialize it with the schema SQL file. procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) 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; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new ADO.Configs.Configuration with null record; -- Get the driver index that corresponds to the driver for this database connection string. function Get_Driver (Config : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) 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; end ADO.Drivers.Connections;
Move the Configuration type in a separate package ADO.Configs so that it is easier to use
Move the Configuration type in a separate package ADO.Configs so that it is easier to use
Ada
apache-2.0
stcarrez/ada-ado
5ff27d2998208e39fe3b0addb5124c55ce77e627
regtests/util-properties-tests.adb
regtests/util-properties-tests.adb
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; begin V := Props.Get (+("missing")); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare V : Util.Properties.Value; P : Properties.Manager; begin P := Util.Properties.To_Manager (V); T.Fail ("No exception raised by To_Manager"); exception when Util.Beans.Objects.Conversion_Error => null; end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_Property; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Remove", Test_Remove_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props); T.Assert (Copy.Exists ("prefix.one"), "Property one not found"); T.Assert (Copy.Exists ("prefix.two"), "Property two not found"); T.Assert (Copy.Exists ("prefix"), "Property '' does not exist."); T.Assert (Copy.Exists ("prefix."), "Property '' does not exist."); end; declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; begin V := Props.Get (+("missing")); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare V : Util.Properties.Value; P : Properties.Manager with Unreferenced; begin P := Util.Properties.To_Manager (V); T.Fail ("No exception raised by To_Manager"); exception when Util.Beans.Objects.Conversion_Error => null; end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_Property; package Caller is new Util.Test_Caller (Test, "Properties"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Remove", Test_Remove_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
Add more test on Copy procedure
Add more test on Copy procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9c84931be3a873d4eda9593b6f927ee5381abeb7
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Set the file modification date. -- ------------------------------ procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec) is begin Element.Date := Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long (Date.tv_sec)); end Set_Date; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Dir_Name : constant String_Access := new String '(Name); Result : constant Directory_Type := new Directory '(-- Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Dir_Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Set the file modification date. -- ------------------------------ procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec) is begin Set_Date (Element, Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long (Date.tv_sec))); end Set_Date; procedure Set_Date (Element : in File_Type; Date : in Ada.Calendar.Time) is use type Ada.Calendar.Time; begin if Element.Date /= Date then Element.Date := Date; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Date; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Implement the Set_Date procedure Store the directory path as a String_Access in the Directory_Type
Implement the Set_Date procedure Store the directory path as a String_Access in the Directory_Type
Ada
apache-2.0
stcarrez/babel
7e07f51601427b72b0aee9856155b89e5c94b026
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Events.Targets.Event_Id_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- 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; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Events.Targets.Event_Id_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Fix the Destroy operation to destroy the node recursively only when the reference counter reaches 0
Fix the Destroy operation to destroy the node recursively only when the reference counter reaches 0
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
93ddf2ff2df2bcb911cd6211aca598c380f38ca4
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- 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. -- -- <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> -- -- 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. -- -- A <tt>Security_Context</tt> can be associated -- -- -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- 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); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- 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. -- -- <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> -- -- 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. -- -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- 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); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Document how to set the roles on a security context
Document how to set the roles on a security context
Ada
apache-2.0
Letractively/ada-security
79e2806e9d15f1978a3508bf8cc61698ea299c7c
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; package body Util.Properties.Bundles is use Util.Log; Log : constant Loggers.Logger := 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); 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; Path : constant String := To_String (Factory.Path); Filter : constant Filter_Type := (Ordinary_File => True, others => False); Pattern : constant String := Name & "*.properties"; Ent : Directory_Entry_Type; Names : Util.Strings.String_Set.Set; Search : Search_Type; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Start_Search (Search, Directory => Path, Pattern => Pattern, Filter => Filter); Factory.Lock.Write; begin -- Scan the directory and load all the property files. while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); File_Path : constant String := Full_Name (Ent); Bundle : constant Bundle_Manager_Access := new Manager; Bundle_Name : constant Name_Access := new String '(Simple (Simple'First .. Simple'Last - 11)); begin Log.Debug ("Loading file {0}", File_Path); Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Found := True; Names.Insert (Bundle_Name); end; end loop; -- 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; -- ------------------------------ -- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; with Util.Strings.Maps; package body Util.Properties.Bundles is use Util.Log; Log : constant Loggers.Logger := 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); 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; Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; Files : Util.Strings.Maps.Map; Iter : Util.Strings.Maps.Cursor; procedure Process_File (Name : in String; File_Path : in String) is Bundle : constant Bundle_Manager_Access := new Manager; Bundle_Name : constant Name_Access := new String '(Name (Name'First .. Name'Last - 11)); begin Log.Debug ("Loading file {0}", File_Path); Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Found := True; Names.Insert (Bundle_Name); end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Util.Files.Find_Files_Path (Pattern => Pattern, Path => Path, Into => Files); Factory.Lock.Write; begin Iter := Files.First; while Util.Strings.Maps.Has_Element (Iter) loop Util.Strings.Maps.Query_Element (Iter, Process_File'Access); Util.Strings.Maps.Next (Iter); end loop; -- 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; -- ------------------------------ -- 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;
Use Find_Files_Path to search the resource bundles in several directories
Use Find_Files_Path to search the resource bundles in several directories
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
adbfe0c044cadcf2e119dc94fc33adaae3236be7
src/util-properties-bundles.ads
src/util-properties-bundles.ads
----------------------------------------------------------------------- -- properties-bundles -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Finalization; with Ada.Containers.Hashed_Maps; with Util.Strings; with Util.Concurrent.Locks; -- == Property bundles == -- Property bundles represent several property files that share some overriding rules and -- capabilities. Their introduction comes from Java resource bundles which allow to -- localize easily some configuration files or some message. When loading a property bundle -- a locale is defined to specify the target language and locale. If a specific property -- file for that locale exists, it is used first. Otherwise, the property bundle will use -- the default property file. -- -- A rule exists on the name of the specific property locale file: it must start with the -- bundle name followed by `_` and the name of the locale. The default property file must -- be the bundle name. For example, the bundle `dates` is associated with the following -- property files: -- -- dates.properties Default values (English locale) -- dates_fr.properties French locale -- dates_de.properties German locale -- dates_es.properties Spain locale -- -- Because a bundle can be associated with one or several property files, a specific loader is -- used. The loader instance must be declared and configured to indicate one or several search -- directories that contain property files. -- -- with Util.Properties.Bundles; -- ... -- Loader : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Util.Properties.Bundles.Initialize (Loader, "bundles;/usr/share/bundles"); -- Util.Properties.Bundles.Load_Bundle (Loader, "dates", "fr", Bundle); -- Ada.Text_IO.Put_Line (Bundle.Get ("util.month1.long"); -- -- In this example, the `util.month1.long` key is first search in the `dates_fr` French locale -- and if it is not found it is searched in the default locale. package Util.Properties.Bundles is NO_BUNDLE : exception; NOT_WRITEABLE : exception; type Manager is new Util.Properties.Manager with private; -- ------------------------------ -- Bundle loader -- ------------------------------ -- The <b>Loader</b> provides facilities for loading property bundles -- and maintains a cache of bundles. The cache is thread-safe but the returned -- bundles are not thread-safe. type Loader is limited private; type Loader_Access is access all Loader; -- Initialize the bundle factory and specify where the property files are stored. procedure Initialize (Factory : in out Loader; Path : in String); -- 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); private procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access); -- Add a bundle type Bundle_Manager_Access is access all Manager'Class; type Manager is new Util.Properties.Manager with null record; overriding procedure Initialize (Object : in out Manager); overriding procedure Adjust (Object : in out Manager); package Bundle_Map is new Ada.Containers.Hashed_Maps (Element_Type => Bundle_Manager_Access, Key_Type => Util.Strings.Name_Access, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); type Loader is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; Bundles : Bundle_Map.Map; Path : Unbounded_String; end record; -- Finalize the bundle loader and clear the cache overriding procedure Finalize (Factory : in out Loader); -- Clear the cache bundle procedure Clear_Cache (Factory : in out Loader); -- 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); -- 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); end Util.Properties.Bundles;
----------------------------------------------------------------------- -- util-properties-bundles -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Finalization; with Ada.Containers.Hashed_Maps; with Util.Strings; with Util.Concurrent.Locks; -- == Property bundles == -- Property bundles represent several property files that share some overriding rules and -- capabilities. Their introduction comes from Java resource bundles which allow to -- localize easily some configuration files or some message. When loading a property bundle -- a locale is defined to specify the target language and locale. If a specific property -- file for that locale exists, it is used first. Otherwise, the property bundle will use -- the default property file. -- -- A rule exists on the name of the specific property locale file: it must start with the -- bundle name followed by `_` and the name of the locale. The default property file must -- be the bundle name. For example, the bundle `dates` is associated with the following -- property files: -- -- dates.properties Default values (English locale) -- dates_fr.properties French locale -- dates_de.properties German locale -- dates_es.properties Spain locale -- -- Because a bundle can be associated with one or several property files, a specific loader is -- used. The loader instance must be declared and configured to indicate one or several search -- directories that contain property files. -- -- with Util.Properties.Bundles; -- ... -- Loader : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Util.Properties.Bundles.Initialize (Loader, "bundles;/usr/share/bundles"); -- Util.Properties.Bundles.Load_Bundle (Loader, "dates", "fr", Bundle); -- Ada.Text_IO.Put_Line (Bundle.Get ("util.month1.long"); -- -- In this example, the `util.month1.long` key is first search in the `dates_fr` French locale -- and if it is not found it is searched in the default locale. package Util.Properties.Bundles is NO_BUNDLE : exception; NOT_WRITEABLE : exception; type Manager is new Util.Properties.Manager with private; -- ------------------------------ -- Bundle loader -- ------------------------------ -- The <b>Loader</b> provides facilities for loading property bundles -- and maintains a cache of bundles. The cache is thread-safe but the returned -- bundles are not thread-safe. type Loader is limited private; type Loader_Access is access all Loader; -- Initialize the bundle factory and specify where the property files are stored. procedure Initialize (Factory : in out Loader; Path : in String); -- 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); private procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access); -- Add a bundle type Bundle_Manager_Access is access all Manager'Class; type Manager is new Util.Properties.Manager with null record; overriding procedure Initialize (Object : in out Manager); overriding procedure Adjust (Object : in out Manager); package Bundle_Map is new Ada.Containers.Hashed_Maps (Element_Type => Bundle_Manager_Access, Key_Type => Util.Strings.Name_Access, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); type Loader is new Ada.Finalization.Limited_Controlled with record Lock : Util.Concurrent.Locks.RW_Lock; Bundles : Bundle_Map.Map; Path : Unbounded_String; end record; -- Finalize the bundle loader and clear the cache overriding procedure Finalize (Factory : in out Loader); -- Clear the cache bundle procedure Clear_Cache (Factory : in out Loader); -- 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); -- 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); end Util.Properties.Bundles;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1af50fdecfe9e3aa84f7d5fed446b0120c5ca8bf
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; package Security.Policies.Roles is -- 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; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); type Role_Policy is new Policy with private; Invalid_Name : exception; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- A role is represented by a name in security configuration files. package Security.Policies.Roles is -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; Invalid_Name : exception; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- 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. overriding procedure Set_Reader_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser); end Security.Policies.Roles;
Define Set_Reader_Config to allow reading the XML configuration for role based policies
Define Set_Reader_Config to allow reading the XML configuration for role based policies
Ada
apache-2.0
Letractively/ada-security
331d50006ae780d9ef87eb296cebedd7628f2879
awa/src/awa-users-services.ads
awa/src/awa-users-services.ads
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); package User_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class); subtype Listener is User_Lifecycle.Listener; NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Kind : in AWA.Users.Models.Key_Type; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; Permissions : AWA.Permissions.Services.Permission_Manager_Access; end record; end AWA.Users.Services;
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 AWA.Users.Models; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); package User_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class); subtype Listener is User_Lifecycle.Listener; NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class; Key : in String := ""); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Kind : in AWA.Users.Models.Key_Type; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; Permissions : AWA.Permissions.Services.Permission_Manager_Access; end record; end AWA.Users.Services;
Add a Key parameter to the Create_User procedure
Add a Key parameter to the Create_User procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f3f2b40b4698049d0a8bd653ec70aa01a476e2de
awa/plugins/awa-questions/src/awa-questions-modules.adb
awa/plugins/awa-questions/src/awa-questions-modules.adb
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with Wiki; with Wiki.Utils; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); 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_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description), Wiki.SYNTAX_MIX); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_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 Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean) is DB : ADO.Sessions.Session := Model.Get_Session; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Delete the answer. -- ------------------------------ procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_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 Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission, Entity => Answer); Answer.Delete (DB); Ctx.Commit; end Delete_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean) is DB : ADO.Sessions.Session := Model.Get_Session; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013, 2015, 2016, 2018, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with Wiki; with Wiki.Utils; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); 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_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description), Wiki.SYNTAX_MARKDOWN); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_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 Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean) is DB : ADO.Sessions.Session := Model.Get_Session; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Delete the answer. -- ------------------------------ procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_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 Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission, Entity => Answer); Answer.Delete (DB); Ctx.Commit; end Delete_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier; Found : out Boolean) is DB : ADO.Sessions.Session := Model.Get_Session; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Modules;
Replace SYNTAX_MIX by SYNTAX_MARKDOWN
Replace SYNTAX_MIX by SYNTAX_MARKDOWN
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f1f027e655e8129e9f2481546b2c71ea7fba6143
src/ado-utils.adb
src/ado-utils.adb
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; -- ------------------------------ -- Compute the hash of the identifier. -- ------------------------------ function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is use Ada.Containers; begin if Key < 0 then return Hash_Type (-Key); else return Hash_Type (Key); end if; end Hash; end ADO.Utils;
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; -- ------------------------------ -- Compute the hash of the identifier. -- ------------------------------ function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is use Ada.Containers; begin if Key < 0 then return Hash_Type (-Key); else return Hash_Type (Key); end if; end Hash; -- ------------------------------ -- Return the identifier list as a comma separated list of identifiers. -- ------------------------------ function To_Parameter_List (List : in Identifier_Vector) return String is use Identifier_Vectors; Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Identifier_Cursor := List.First; Need_Comma : Boolean := False; begin while Identifier_Vectors.Has_Element (Pos) loop if Need_Comma then Ada.Strings.Unbounded.Append (Result, ","); end if; Ada.Strings.Unbounded.Append (Result, ADO.Identifier'Image (Element (Pos))); Need_Comma := True; Next (Pos); end loop; return Ada.Strings.Unbounded.To_String (Result); end To_Parameter_List; end ADO.Utils;
Implement the To_Parameter_List operation
Implement the To_Parameter_List operation
Ada
apache-2.0
stcarrez/ada-ado
0cca1830e31b14d7880b5f0220c08350aac8806e
awa/plugins/awa-mail/src/awa-mail-modules.ads
awa/plugins/awa-mail/src/awa-mail-modules.ads
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Documentation == -- The *mail* module allows an application to format and send a mail -- to users. This module does not define any web interface. It provides -- a set of services and methods to send a mail when an event is -- received. All this is done through configuration. The module -- defines a set of specific ASF components to format and prepare the -- email. -- -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- ||mail.smtp.host||localhost||Defines the SMTP server host name|| -- ||mail.smtp.port||25||Defines the SMTP connection port|| -- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not|| -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Get the mail template that must be used for the given event name. -- The mail template is configured by the property: <i>module</i>.template.<i>event</i>. function Get_Template (Plugin : in Mail_Module; Name : in String) return String; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
----------------------------------------------------------------------- -- awa-mail -- Mail module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Documentation == -- The *mail* module allows an application to format and send a mail -- to users. This module does not define any web interface. It provides -- a set of services and methods to send a mail when an event is -- received. All this is done through configuration. The module -- defines a set of specific ASF components to format and prepare the -- email. -- -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- ||mail.smtp.host||localhost||Defines the SMTP server host name|| -- ||mail.smtp.port||25||Defines the SMTP connection port|| -- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not|| -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- -- == Ada Beans == -- @include mail.xml -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Get the mail template that must be used for the given event name. -- The mail template is configured by the property: <i>module</i>.template.<i>event</i>. function Get_Template (Plugin : in Mail_Module; Name : in String) return String; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
Add the Ada beans in the mail plugin documentation
Add the Ada beans in the mail plugin documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
72aadafb8581768c2abfd9c540e1811149630d31
src/wiki-helpers.adb
src/wiki-helpers.adb
----------------------------------------------------------------------- -- 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 Ada.Wide_Wide_Characters.Handling; with Ada.Wide_Wide_Characters.Unicode; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a punctuation character. -- ------------------------------ function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Unicode.Is_Punctuation (C); end Is_Punctuation; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- 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 is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- 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 is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; -- ------------------------------ -- 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) is Pos : Natural; Last : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" or Dimension = "upright" then Width := 800; Height := 0; else Pos := Wiki.Strings.Index (Dimension, "x"); Last := Wiki.Strings.Index (Dimension, "px"); if Pos > Dimension'First and Last + 1 /= Pos then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1)); elsif Last > 0 then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1)); else Height := 0; end if; end if; exception when Constraint_Error => Width := 0; Height := 0; end Get_Sizes; -- ------------------------------ -- 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 is Pos : Positive := From; begin while Pos <= Text'Last and then Is_Space (Text (Pos)) loop Pos := Pos + 1; end loop; return Pos; end Skip_Spaces; -- ------------------------------ -- Find the position of the last non space character scanning the text backward -- from the given position. Returns Text'First - 1 if the text only contains spaces. -- ------------------------------ function Trim_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Natural is Pos : Natural := From; begin while Pos >= Text'First and then Is_Space (Text (Pos)) loop Pos := Pos - 1; end loop; return Pos; end Trim_Spaces; 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 Ada.Wide_Wide_Characters.Handling; with Ada.Wide_Wide_Characters.Unicode; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT or C = NBSP; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a punctuation character. -- ------------------------------ function Is_Punctuation (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Unicode.Is_Punctuation (C); end Is_Punctuation; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- 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 is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- 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 is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; -- ------------------------------ -- 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) is Pos : Natural; Last : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" or Dimension = "upright" then Width := 800; Height := 0; else Pos := Wiki.Strings.Index (Dimension, "x"); Last := Wiki.Strings.Index (Dimension, "px"); if Pos > Dimension'First and Last + 1 /= Pos then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1)); elsif Last > 0 then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1)); else Height := 0; end if; end if; exception when Constraint_Error => Width := 0; Height := 0; end Get_Sizes; -- ------------------------------ -- 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 is Pos : Positive := From; begin while Pos <= Text'Last and then Is_Space (Text (Pos)) loop Pos := Pos + 1; end loop; return Pos; end Skip_Spaces; -- ------------------------------ -- Find the position of the last non space character scanning the text backward -- from the given position. Returns Text'First - 1 if the text only contains spaces. -- ------------------------------ function Trim_Spaces (Text : in Wiki.Strings.Wstring; From : in Positive) return Natural is Pos : Natural := From; begin while Pos >= Text'First and then Is_Space (Text (Pos)) loop Pos := Pos - 1; end loop; return Pos; end Trim_Spaces; -- ------------------------------ -- Find the position of the given character in the string starting at the given position. -- ------------------------------ function Index (Text : in Wiki.Strings.Wstring; Item : in Wiki.Strings.Wchar; From : in Positive) return Natural is Pos : Natural := From; begin while Pos <= Text'Last loop if Text (Pos) = Item then return Pos; end if; Pos := Pos + 1; end loop; return 0; end Index; end Wiki.Helpers;
Add Index function
Add Index function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3dfbdfd61bf0367ee3c0b3a01444175f179355d2
awa/src/awa-users-filters.ads
awa/src/awa-users-filters.ads
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "user.auth-filter.redirect"; -- A temporary cookie used to store the URL for redirection after the login is successful. REDIRECT_COOKIE : constant String := "RURL"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "user.verify-filter.redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "redirect"; -- A temporary cookie used to store the URL for redirection after the login is successful. REDIRECT_COOKIE : constant String := "RURL"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
Rename the configuration parameters to simplify their names
Rename the configuration parameters to simplify their names
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ab8e77a50baee7b694d14be8cd35d97c21e5bd82
awa/src/awa-users-modules.ads
awa/src/awa-users-modules.ads
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ASF.Security.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include users.xml -- -- @include awa-users-services.ads -- -- @include users.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_user_model.png] -- -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 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 ASF.Applications; with ASF.Security.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include users.xml -- -- @include awa-users-services.ads -- -- @include users.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_user_model.png] -- -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased AWA.Users.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
Use the authenticate servlet defined in the AWA.Users.Servlets package
Use the authenticate servlet defined in the AWA.Users.Servlets package
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
a7b03e9f105178041e5089b937ef416415c3acff
ARM/STMicro/STM32/drivers/stm32-rng-polling.adb
ARM/STMicro/STM32/drivers/stm32-rng-polling.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4xx_hal_rng.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief RNG HAL module driver. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ package body STM32.RNG.Polling is -------------------- -- Initialize_RNG -- -------------------- procedure Initialize_RNG is Discard : Unsigned_32; begin Enable_RNG_Clock; Enable_RNG; -- Discard the first randomly generated number, according to STM32F4 -- docs. Discard := Random; end Initialize_RNG; ------------ -- Random -- ------------ function Random return Interfaces.Unsigned_32 is begin while RNG_Data_Ready loop null; end loop; return RNG_Data; end Random; end STM32.RNG.Polling;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4xx_hal_rng.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief RNG HAL module driver. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ package body STM32.RNG.Polling is -------------------- -- Initialize_RNG -- -------------------- procedure Initialize_RNG is Discard : Unsigned_32; begin Enable_RNG_Clock; Enable_RNG; -- Discard the first randomly generated number, according to STM32F4 -- docs. Discard := Random; end Initialize_RNG; ------------ -- Random -- ------------ function Random return Interfaces.Unsigned_32 is begin while not RNG_Data_Ready loop null; end loop; return RNG_Data; end Random; end STM32.RNG.Polling;
Fix STM32.RNG.Polling
Fix STM32.RNG.Polling
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
87fab60c968ebcf03a7233d6566c3b8de3079bc7
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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_HAS_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; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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_HAS_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; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Update Is_Selected to handle N_NO_FREE and accept the event only if the event is a malloc/realloc and does not have an associated free/realloc
Update Is_Selected to handle N_NO_FREE and accept the event only if the event is a malloc/realloc and does not have an associated free/realloc
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d6985e7a86d427b00861beb315d19525e97edfa4
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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_HAS_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; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- 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; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- 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 Ada.Strings.Unbounded.Unbounded_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 => 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_HAS_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; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- 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 True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); 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; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.Targets.MSG_MALLOC or Event.Index = MAT.Events.Targets.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Implement the Create_No_Free function
Implement the Create_No_Free function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0ea24d8977dc292bd3784554fe339d9da12de67f
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
Declare Is_On function
Declare Is_On function
Ada
apache-2.0
stcarrez/ada-ado
bad589d1cf97d1dedcc2b1d1b70a3c92df36e231
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Conversions; with Interfaces.C; with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Set the owner and group of the file. -- ------------------------------ procedure Set_Owner (Element : in File_Type; User : in Uid_Type; Group : in Gid_Type) is begin Element.User := User; Element.Group := Group; end Set_Owner; -- ------------------------------ -- Set the file modification date. -- ------------------------------ procedure Set_Date (Element : in File_Type; Date : in Util.Systems.Types.Timespec) is begin Element.Date := Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long (Date.tv_sec)); end Set_Date; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Return the file unix mode. -- ------------------------------ function Get_Mode (Element : in File_Type) return File_Mode is begin return Element.Mode; end Get_Mode; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Implement the Set_Date operation
Implement the Set_Date operation
Ada
apache-2.0
stcarrez/babel
4f2a8bec74f5d43143834499b307a57e8524f81d
mat/src/symbols/mat-symbols-targets.ads
mat/src/symbols/mat-symbols-targets.ads
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Bfd.Symbols; with Bfd.Files; with Util.Refs; with MAT.Types; package MAT.Symbols.Targets is type Target_Symbols is new Util.Refs.Ref_Entity with record File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Name : out Ada.Strings.Unbounded.Unbounded_String; Func : out Ada.Strings.Unbounded.Unbounded_String; Line : out Natural); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Bfd.Symbols; with Bfd.Files; with Util.Refs; with MAT.Types; package MAT.Symbols.Targets is type Target_Symbols is new Util.Refs.Ref_Entity with record File : Bfd.Files.File_Type; Symbols : Bfd.Symbols.Symbol_Table; end record; type Target_Symbols_Access is access all Target_Symbols; -- Open the binary and load the symbols from that file. procedure Open (Symbols : in out Target_Symbols; Path : in String); -- Find the nearest source file and line for the given address. procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Name : out Ada.Strings.Unbounded.Unbounded_String; Func : out Ada.Strings.Unbounded.Unbounded_String; Line : out Natural); package Target_Symbols_Refs is new Util.Refs.References (Target_Symbols, Target_Symbols_Access); subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref; end MAT.Symbols.Targets;
Declare Target_Symbols_Ref subtype
Declare Target_Symbols_Ref subtype
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8296dc1f0f03f51a68ff9eaa23b3043208eef296
src/base/os-windows/util-systems-os.ads
src/base/os-windows/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019, 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; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; type Process_Identifier is new Integer; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := 16#fffffff6#; STD_OUTPUT_HANDLE : constant DWORD := 16#fffffff5#; STD_ERROR_HANDLE : constant DWORD := 16#fffffff4#; -- 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; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lstat (Path : in String; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_lstat64"; 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; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer with Import => True, Convention => C, Link_Name => "rename"; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => "unlink"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019, 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; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; type Process_Identifier is new Integer; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := 16#fffffff6#; STD_OUTPUT_HANDLE : constant DWORD := 16#fffffff5#; STD_ERROR_HANDLE : constant DWORD := 16#fffffff4#; -- 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; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lstat (Path : in String; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; 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; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer with Import => True, Convention => C, Link_Name => "rename"; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => "unlink"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Fix for Windows
Fix for Windows
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6f5cd876db5d3ca9473e1dc96cb432c667a548a8
src/asf-views-facelets.adb
src/asf-views-facelets.adb
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 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 Ada.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Root = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Res : Facelet; Fname : constant Unbounded_String := To_Unbounded_String (Name); begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Fname, Res); if Res.Root = null then Load (Factory, Name, Context, Res); if Res.Root = null then Result.Root := null; return; end if; Update (Factory, Fname, Res); end if; Result.Root := Res.Root; Result.File := Res.File; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Root /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all), Previous => Old); View.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Root := null; Result := Factory.Map.Find (Name); if Result.Root /= null and then Modification_Time (Result.File.Path) > Result.Modify_Time then Result.Root := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.File.Path); end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if Path = "" or else not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Root := null; return; end if; declare Pos : constant Integer := Path'Last - Name'Length + 1; File : File_Info_Access; Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; begin if Pos <= Path'First then File := Create_File_Info (Path, Path'First); else File := Create_File_Info (Path, Pos); end if; Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Result.Root := Reader.Get_Root; Result.File := File; if File = null then if Result.Root /= null then Result.Root.Delete; end if; Result.Root := null; else Result.Modify_Time := Mtime; end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet) is begin Factory.Map.Insert (Name, Item); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in Unbounded_String) return Facelet is Pos : constant Facelet_Maps.Cursor := Map.Find (Name); begin if Facelet_Maps.Has_Element (Pos) then return Element (Pos); else return Empty; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Name : in Unbounded_String; Item : in Facelet) is begin Map.Include (Name, Item); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Maps.Cursor := Map.First; Node : Facelet; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014, 2015, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Facelet_Type, Name => Facelet_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Facelet : in Facelet_Access); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Facelet = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Name, Result); if Result.Facelet = null then Load (Factory, Name, Context, Result); if Result.Facelet = null then return; end if; Update (Factory, Result.Facelet); end if; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Facelet /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.Facelet.File.all), Previous => Old); View.Facelet.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Facelet := Factory.Map.Find (Name); if Result.Facelet /= null then declare Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin if Result.Facelet.Check_Time < Now then if Modification_Time (Result.Facelet.File.Path) > Result.Facelet.Modify_Time then Result.Facelet := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.Facelet.File.Path); else Result.Facelet.Check_Time := Now + CHECK_FILE_DELAY; end if; end if; end; end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if Path = "" or else not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Facelet := null; return; end if; declare use type Ada.Calendar.Time; Pos : constant Integer := Path'Last - Name'Length + 1; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock + CHECK_FILE_DELAY; File : File_Info_Access; Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; Root : ASF.Views.Nodes.Tag_Node_Access; begin if Pos <= Path'First then File := Create_File_Info (Path, Path'First); else File := Create_File_Info (Path, Pos); end if; Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Root := Reader.Get_Root; if File = null then if Root /= null then Root.Delete; end if; Result.Facelet := null; else Result.Facelet := new Facelet_Type '(Util.Refs.Ref_Entity with Len => Name'Length, Root => Root, File => File, Modify_Time => Mtime, Check_Time => Now, Name => Name); end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Facelet : in Facelet_Access) is begin Factory.Map.Insert (Facelet); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in String) return Facelet_Access is Key : aliased Facelet_Type := Facelet_Type '(Util.Refs.Ref_Entity with Len => Name'Length, Name => Name, others => <>); Pos : constant Facelet_Sets.Cursor := Map.Find (Key'Unchecked_Access); begin if Facelet_Sets.Has_Element (Pos) then return Element (Pos); else return null; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Facelet : in Facelet_Access) is begin Map.Include (Facelet); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Sets.Cursor := Map.First; Node : Facelet_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); Free (Node); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
Refactor Facelet_Type to avoir checking the file date change each time the facelet is fetch - store the facelet name within the record - update Check_Time and use it to avoid checking the file modification time if the Check_Time was not been reached yet
Refactor Facelet_Type to avoir checking the file date change each time the facelet is fetch - store the facelet name within the record - update Check_Time and use it to avoid checking the file modification time if the Check_Time was not been reached yet
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7c5fafab2fc5f89857355887a651cefa1ca81b3f
src/util-dates.ads
src/util-dates.ads
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Month_Day : Ada.Calendar.Day_Number; Day : Ada.Calendar.Formatting.Day_Name; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Sub_Second : Ada.Calendar.Formatting.Second_Duration; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset; Leap_Second : Boolean; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; -- = Date Utilities = -- The `Util.Dates` package provides various date utilities to help in formatting and parsing -- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and -- other packages by implementing specific formatting and parsing. -- -- == Date Operations == -- Several operations allow to compute: -- -- * The start of the day (0:00), -- * The end of the day (24:00), -- * The start of the week, -- * The end of the week, -- * The start of the month, -- * The end of the month -- -- @include util-dates-rfc7231.ads -- @include util-dates-iso8601.ads -- @include util-dates-formats.ads package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Month_Day : Ada.Calendar.Day_Number; Day : Ada.Calendar.Formatting.Day_Name; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Sub_Second : Ada.Calendar.Formatting.Second_Duration; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset; Leap_Second : Boolean; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
Add and update the documentation
Add and update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
dc948740eeac28ca03b8d5588ac2936fde322531
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation 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); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation 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); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
Define the Finish_Document procedure
Define the Finish_Document procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
a644fb2f6b385d75c676ce2d1cd5a42d515bd399
mat/src/mat-consoles-text.ads
mat/src/mat-consoles-text.ads
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package MAT.Consoles.Text is type Console_Type is new MAT.Consoles.Console_Type with private; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Console_Type is new MAT.Consoles.Console_Type with record File : Ada.Text_IO.File_Type; end record; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014, 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.Text_IO; package MAT.Consoles.Text is type Console_Type is new MAT.Consoles.Console_Type with private; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Console_Type is new MAT.Consoles.Console_Type with record File : Ada.Text_IO.File_Type; Cur_Col : Ada.Text_IO.Count := 0; end record; end MAT.Consoles.Text;
Add Cur_Col to track the current column (the Ada Text_IO current column tracking does not work with ANSI colors)
Add Cur_Col to track the current column (the Ada Text_IO current column tracking does not work with ANSI colors)
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c294530a76dea5a863a9901df721744a5eeb3271
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; 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_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access); -- 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; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access) is -- -- use ASF.Views; -- -- Tree : Facelets.Facelet; -- begin -- Facelets.Find_Facelet (Factory => Context.Facelets.all, -- Name => Ada.Strings.Unbounded.To_String (Name), -- Result => Tree); -- -- Facelets.Build_View (View => Tree, -- Context => Context, -- Root => Parent); -- end Include_Definition; -- ------------------------------ -- 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 To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); 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; 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 Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; 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); 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; -- ------------------------------ -- 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; -- ------------------------------ -- Register a module -- ------------------------------ procedure Register_Module (Handler : in out View_Handler; Module : in ASF.Modules.Module_Access) is use Ada.Strings.Unbounded; Name : constant String := Module.Get_Name; URI : constant String := Module.Get_URI; Def : constant String := To_String (Handler.Paths) & "/" & URI; Dir : constant String := Module.Get_Config (Name & ".web.dir", Def); begin ASF.Views.Facelets.Register_Module (Handler.Facelets, URI, Dir); end Register_Module; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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.Fixed; with Util.Files; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; 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_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access); -- 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; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access) is -- -- use ASF.Views; -- -- Tree : Facelets.Facelet; -- begin -- Facelets.Find_Facelet (Factory => Context.Facelets.all, -- Name => Ada.Strings.Unbounded.To_String (Name), -- Result => Tree); -- -- Facelets.Build_View (View => Tree, -- Context => Context, -- Root => Parent); -- end Include_Definition; -- ------------------------------ -- 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 To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); 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; 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 Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; 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); 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; -- ------------------------------ -- 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; -- ------------------------------ -- Register a module -- ------------------------------ procedure Register_Module (Handler : in out View_Handler; Module : in ASF.Modules.Module_Access) is use Ada.Strings.Unbounded; Name : constant String := Module.Get_Name; URI : constant String := Module.Get_URI; Def : constant String := Util.Files.Compose_Path (To_String (Handler.Paths), URI); Dir : constant String := Module.Get_Config (Name & ".web.dir", Def); begin ASF.Views.Facelets.Register_Module (Handler.Facelets, URI, Dir); end Register_Module; end ASF.Applications.Views;
Use Compose_Path to create the module specific search path
Use Compose_Path to create the module specific search path
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
4b87608f26408d2c40be5b506bacea0f5cf62062
src/wiki-render.adb
src/wiki-render.adb
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Render is -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish (Doc); end Render; end Wiki.Render;
----------------------------------------------------------------------- -- wiki-render -- Wiki renderer -- Copyright (C) 2015, 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes.Lists; package body Wiki.Render is -- ------------------------------ -- Render the list of nodes from the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document; List : in Wiki.Nodes.Node_List_Access) is use type Wiki.Nodes.Node_List_Access; procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin if List /= null then Wiki.Nodes.Lists.Iterate (List, Process'Access); end if; end Render; -- ------------------------------ -- Render the document. -- ------------------------------ procedure Render (Engine : in out Renderer'Class; Doc : in Wiki.Documents.Document) is procedure Process (Node : in Wiki.Nodes.Node_Type); procedure Process (Node : in Wiki.Nodes.Node_Type) is begin Engine.Render (Doc, Node); end Process; begin Doc.Iterate (Process'Access); Engine.Finish (Doc); end Render; end Wiki.Render;
Update to use the new Node_List_Ref reference
Update to use the new Node_List_Ref reference
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
96bd5193fddaf424f97757d4d7405b89d529396a
src/base/files/util-files.ads
src/base/files/util-files.ads
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; 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 in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. function Find_File_Path (Name : String; Paths : 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 ';'. -- 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) 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 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;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
73259ba38381c745747e7243150921db0e9779c6
src/util-commands-drivers.adb
src/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class) is begin Put_Line (To_String (Driver.Desc)); New_Line; Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class) is begin Put_Line (To_String (Driver.Desc)); New_Line; Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Fix compilation style warnings
Fix compilation style warnings
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c469c16925b263d1dc70a82499d3d5a52569ccc6
src/gen-model.ads
src/gen-model.ads
----------------------------------------------------------------------- -- gen-model -- Model for Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with DOM.Core; package Gen.Model is -- Exception raised if a name is already registered in the model. -- This exception is raised if a table, an enum is already defined. Name_Exist : exception; -- ------------------------------ -- Model Definition -- ------------------------------ type Definition is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; type Definition_Access is access all Definition'Class; -- Prepare the generation of the model. procedure Prepare (O : in out Definition) is null; -- Get the object unique name. function Get_Name (From : in Definition) return String; function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String; -- Set the object unique name. procedure Set_Name (Def : in out Definition; Name : in String); procedure Set_Name (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String); -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Definition; Name : in String) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Attribute (From : in Definition; Name : in String) return String; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Attribute (From : in Definition; Name : in String) return Ada.Strings.Unbounded.Unbounded_String; -- Set the comment associated with the element. procedure Set_Comment (Def : in out Definition; Comment : in String); -- Get the comment associated with the element. function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object; -- Set the location (file and line) where the model element is defined in the XMI file. procedure Set_Location (Node : in out Definition; Location : in String); -- Get the location file and line where the model element is defined. function Get_Location (Node : in Definition) return String; -- Initialize the definition from the DOM node attributes. procedure Initialize (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String; Node : in DOM.Core.Node); private type Definition is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Row_Index : Natural; Def_Name : Ada.Strings.Unbounded.Unbounded_String; Attrs : Util.Beans.Objects.Maps.Map_Bean; Comment : Util.Beans.Objects.Object; Location : Ada.Strings.Unbounded.Unbounded_String; end record; end Gen.Model;
----------------------------------------------------------------------- -- gen-model -- Model for Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Util.Log; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with DOM.Core; package Gen.Model is -- Exception raised if a name is already registered in the model. -- This exception is raised if a table, an enum is already defined. Name_Exist : exception; -- ------------------------------ -- Model Definition -- ------------------------------ type Definition is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; type Definition_Access is access all Definition'Class; -- Prepare the generation of the model. procedure Prepare (O : in out Definition) is null; -- Get the object unique name. function Get_Name (From : in Definition) return String; function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String; -- Set the object unique name. procedure Set_Name (Def : in out Definition; Name : in String); procedure Set_Name (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String); -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Definition; Name : in String) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Attribute (From : in Definition; Name : in String) return String; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Attribute (From : in Definition; Name : in String) return Ada.Strings.Unbounded.Unbounded_String; -- Set the comment associated with the element. procedure Set_Comment (Def : in out Definition; Comment : in String); -- Get the comment associated with the element. function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object; -- Set the location (file and line) where the model element is defined in the XMI file. procedure Set_Location (Node : in out Definition; Location : in String); -- Get the location file and line where the model element is defined. function Get_Location (Node : in Definition) return String; -- Initialize the definition from the DOM node attributes. procedure Initialize (Def : in out Definition; Name : in Ada.Strings.Unbounded.Unbounded_String; Node : in DOM.Core.Node); -- Validate the definition by checking and reporting problems to the logger interface. procedure Validate (Def : in out Definition; Log : in out Util.Log.Logging'Class); private type Definition is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Row_Index : Natural; Def_Name : Ada.Strings.Unbounded.Unbounded_String; Attrs : Util.Beans.Objects.Maps.Map_Bean; Comment : Util.Beans.Objects.Object; Location : Ada.Strings.Unbounded.Unbounded_String; end record; end Gen.Model;
Declare the Validate procedure to add some validation and report errors on a model
Declare the Validate procedure to add some validation and report errors on a model
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4785534894e57cdf352f9cd7f025a1cd7e1eab45
mat/src/mat-targets-probes.adb
mat/src/mat-targets-probes.adb
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0; MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; M_HEAP_START : constant MAT.Events.Internal_Reference := 3; M_HEAP_END : constant MAT.Events.Internal_Reference := 4; M_END : constant MAT.Events.Internal_Reference := 5; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; HP_START_NAME : aliased constant String := "hp_start"; HP_END_NAME : aliased constant String := "hp_end"; END_NAME : aliased constant String := "end"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE), 3 => (Name => HP_START_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START), 4 => (Name => HP_END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END), 5 => (Name => END_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_END)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Addr; 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_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MSG_BEGIN then Probe.Probe_Begin (Event.Index, Params.all, Msg); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes"); MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0; MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1; MSG_LIBRARY : constant MAT.Events.Targets.Probe_Index_Type := 2; 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; M_LIBNAME : constant MAT.Events.Internal_Reference := 6; M_LADDR : constant MAT.Events.Internal_Reference := 7; M_COUNT : constant MAT.Events.Internal_Reference := 8; M_TYPE : constant MAT.Events.Internal_Reference := 9; M_VADDR : constant MAT.Events.Internal_Reference := 10; M_SIZE : constant MAT.Events.Internal_Reference := 11; 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"; LIBNAME_NAME : aliased constant String := "libname"; LADDR_NAME : aliased constant String := "laddr"; COUNT_NAME : aliased constant String := "count"; TYPE_NAME : aliased constant String := "type"; VADDR_NAME : aliased constant String := "vaddr"; SIZE_NAME : aliased constant String := "size"; 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)); Library_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => LIBNAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME), 2 => (Name => LADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_LADDR), 3 => (Name => COUNT_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_COUNT), 4 => (Name => TYPE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_TYPE), 5 => (Name => VADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_VADDR), 6 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_SIZE)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (Probe : in Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin Probe.Target.Create_Process (Pid => Pid, Path => Path, Process => Probe.Target.Current); Probe.Target.Process.Events := Probe.Events; MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory, Manager => Probe.Manager.all); end Create_Process; procedure Probe_Begin (Probe : in Process_Probe_Type; Id : in MAT.Events.Targets.Probe_Index_Type; Defs : in MAT.Events.Attribute_Table; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Addr; 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_Process_Ref (Msg, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg); when M_HEAP_START => Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when M_HEAP_END => Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when others => MAT.Readers.Marshaller.Skip (Msg, Def.Size); end case; end; end loop; Heap.Size := Heap.End_Addr - Heap.Start_Addr; Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]"); Probe.Create_Process (Pid, Path); Probe.Manager.Read_Message (Msg); Probe.Manager.Read_Event_Definitions (Msg); Probe.Target.Process.Memory.Add_Region (Heap); end Probe_Begin; overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type) is use type MAT.Events.Targets.Probe_Index_Type; begin if Event.Index = MSG_BEGIN then Probe.Probe_Begin (Event.Index, Params.all, Msg); end if; end Extract; procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type) is begin null; end Execute; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access) is begin Probe.Manager := Into'Unchecked_Access; Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "end", MSG_END, Process_Attributes'Access); Into.Register_Probe (Probe.all'Access, "shlib", MSG_LIBRARY, Library_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Process_Probe : constant Process_Probe_Type_Access := new Process_Probe_Type; begin Process_Probe.Target := Target'Unrestricted_Access; Process_Probe.Events := Manager.Get_Target_Events; Register (Manager, Process_Probe); end Initialize; end MAT.Targets.Probes;
Declare the Library_Attributes array with the description of shared library event Register the Library_Attributes instance
Declare the Library_Attributes array with the description of shared library event Register the Library_Attributes instance
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
af73c7deba99efc9598b0e7da9a90a0c029d61ee
regtests/ado-datasets-tests.adb
regtests/ado-datasets-tests.adb
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 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.Test_Caller; with Util.Properties; with Regtests.Simple.Model; with Regtests.Statements.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.List (<sql> with null)", Test_List_Nullable'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; -- ------------------------------ -- Test dataset lists with null columns. -- ------------------------------ procedure Test_List_Nullable (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_SQL ("SELECT COUNT(*) FROM test_nullable_table"); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare Item : Regtests.Statements.Model.Nullable_Table_Ref; begin Item.Set_Bool_Value (False); if (I mod 2) = 0 then Item.Set_Int_Value (ADO.Nullable_Integer '(123, False)); end if; if (I mod 4) = 0 then Item.Set_Time_Value (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Item.Save (DB); end; end loop; DB.Commit; Query.Set_SQL ("SELECT * FROM test_nullable_table"); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List_Nullable; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013, 2014, 2015, 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 Regtests.Simple.Model; with Regtests.Statements.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.List (<sql> with null)", Test_List_Nullable'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; -- ------------------------------ -- Test dataset lists with null columns. -- ------------------------------ procedure Test_List_Nullable (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_SQL ("SELECT COUNT(*) FROM test_nullable_table"); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare Item : Regtests.Statements.Model.Nullable_Table_Ref; begin Item.Set_Bool_Value (False); if (I mod 2) = 0 then Item.Set_Int_Value (ADO.Nullable_Integer '(123, False)); end if; if (I mod 4) = 0 then Item.Set_Time_Value (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Item.Save (DB); end; end loop; DB.Commit; Query.Set_SQL ("SELECT * FROM test_nullable_table"); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List_Nullable; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
Remove unused Properties
Remove unused Properties
Ada
apache-2.0
stcarrez/ada-ado
dab939cfadd97fb87549b19373b7221cbf7f1964
regtests/el-expressions-tests.adb
regtests/el-expressions-tests.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- 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 AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- 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 AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
Add unit test for Reduce_Expression
Add unit test for Reduce_Expression
Ada
apache-2.0
stcarrez/ada-el
453c46ef4a4ce0f0efe56ec3ea3fc53380249abd
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Implement the Stop operation
Implement the Stop operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d2ec04b807bcbc315bfc62b5e620c27fd22a4dda
mat/src/mat-readers-streams-sockets.ads
mat/src/mat-readers-streams-sockets.ads
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers.Doubly_Linked_Lists; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Client : GNAT.Sockets.Socket_Type; Stop : Boolean := False; end record; package Socket_Client_Lists is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Socket_Reader_Type_Access); type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; Clients : Socket_Client_Lists.List; end record; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers.Doubly_Linked_Lists; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Readers.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Client : GNAT.Sockets.Socket_Type; Stop : Boolean := False; end record; package Socket_Client_Lists is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Socket_Reader_Type_Access); type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record List : MAT.Readers.Reader_List_Type_Access; Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; Clients : Socket_Client_Lists.List; end record; end MAT.Readers.Streams.Sockets;
Add the Reader_List_Type instance to the Start operation and keep it in the socket listener type
Add the Reader_List_Type instance to the Start operation and keep it in the socket listener type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ad5f598a5a6d99a236054747dccd1f295fe74be9
mat/regtests/mat-testsuite.adb
mat/regtests/mat-testsuite.adb
----------------------------------------------------------------------- -- mat-testsuite - MAT Testsuite -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Readers.Tests; with MAT.Targets.Tests; with MAT.Frames.Tests; with MAT.Memory.Tests; package body MAT.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin MAT.Frames.Tests.Add_Tests (Result); MAT.Memory.Tests.Add_Tests (Result); MAT.Readers.Tests.Add_Tests (Result); MAT.Targets.Tests.Add_Tests (Result); return Result; end Suite; end MAT.Testsuite;
----------------------------------------------------------------------- -- mat-testsuite - MAT Testsuite -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Readers.Tests; with MAT.Targets.Tests; with MAT.Frames.Tests; with MAT.Memory.Tests; with MAT.Expressions.Tests; package body MAT.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Result : constant Util.Tests.Access_Test_Suite := Tests'Access; begin MAT.Expressions.Tests.Add_Tests (Result); MAT.Frames.Tests.Add_Tests (Result); MAT.Memory.Tests.Add_Tests (Result); MAT.Readers.Tests.Add_Tests (Result); MAT.Targets.Tests.Add_Tests (Result); return Result; end Suite; end MAT.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2193bb8bc7e34179673af1af26ffff5470a0daa8
src/yaml.ads
src/yaml.ads
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is private; -- Reference to a node as part of a document No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Scalar_Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Sequence_Length (Node : Node_Ref) return Natural with Pre => Kind (Node) = Sequence_Node; -- Return the number of items in the Node sequence function Sequence_Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node; -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Mapping_Length (Node : Node_Ref) return Natural with Pre => Kind (Node) = Mapping_Node; -- Return the number of key/value associations in the Node mapping function Mapping_Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node; -- Return the Index'th key/value association in Node. Index is 1-based. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; To_Delete : Boolean; end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is private; -- Reference to a node as part of a document. Such values must not outlive -- the value for the document that owns them. No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Scalar_Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Sequence_Length (Node : Node_Ref) return Natural with Pre => Kind (Node) = Sequence_Node; -- Return the number of items in the Node sequence function Sequence_Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node; -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Mapping_Length (Node : Node_Ref) return Natural with Pre => Kind (Node) = Mapping_Node; -- Return the number of key/value associations in the Node mapping function Mapping_Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node; -- Return the Index'th key/value association in Node. Index is 1-based. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; To_Delete : Boolean; end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
Enhance comment for YAML.Node_Ref
Enhance comment for YAML.Node_Ref
Ada
mit
pmderodat/libyaml-ada,pmderodat/libyaml-ada
34261786aa3d8e9f9e7ce1400a12ebaaa4de2cd9
regtests/asf-security-tests.adb
regtests/asf-security-tests.adb
----------------------------------------------------------------------- -- asf-security-tests - Unit tests for ASF.Security -- 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 Security.Policies; use Security; with Security.Policies.URLs; with ASF.Servlets; with ASF.Servlets.Tests; with ASF.Security.Filters; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Security.Tests is use Util.Tests; -- ------------------------------ -- Check that the given URI reports the HTTP status. -- ------------------------------ procedure Check_Security (T : in out Test; URI : in String; Result : in Natural) is Ctx : ASF.Servlets.Servlet_Registry; S1 : aliased ASF.Servlets.Tests.Test_Servlet1; F1 : aliased ASF.Security.Filters.Auth_Filter; Sec : aliased Policies.Policy_Manager (Max_Policies => 10); begin F1.Set_Permission_Manager (Sec'Unchecked_Access); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Filter ("Security", F1'Unchecked_Access); Sec.Add_Policy (new Policies.URLs.URL_Policy); Sec.Read_Policy (Util.Tests.Get_Path ("regtests/files/permissions/simple-policy.xml")); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Filter_Mapping (Pattern => "*.jsf", Name => "Security"); declare Dispatcher : constant ASF.Servlets.Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI & ".jsf"); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; begin Req.Set_Request_URI ("/admin/test"); Req.Set_Method ("GET"); ASF.Servlets.Forward (Dispatcher, Req, Resp); Assert_Equals (T, Result, Resp.Get_Status, "Invalid status"); end; end Check_Security; -- ------------------------------ -- Test the security filter granting permission for a given URI. -- ------------------------------ procedure Test_Security_Filter (T : in out Test) is begin T.Check_Security ("/admin/test", ASF.Responses.SC_UNAUTHORIZED); end Test_Security_Filter; -- ------------------------------ -- Test the security filter grants access to anonymous allowed pages. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Check_Security ("/view", ASF.Responses.SC_OK); end Test_Anonymous_Access; package Caller is new Util.Test_Caller (Test, "Security"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Security.Filters.Auth_Filter (deny)", Test_Security_Filter'Access); Caller.Add_Test (Suite, "Test ASF.Security.Filters.Auth_Filter (grant)", Test_Anonymous_Access'Access); end Add_Tests; end ASF.Security.Tests;
----------------------------------------------------------------------- -- asf-security-tests - Unit tests for ASF.Security -- Copyright (C) 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 Security.Policies; use Security; with Security.Policies.URLs; with ASF.Servlets; with ASF.Servlets.Tests; with ASF.Security.Filters; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Security.Tests is use Util.Tests; -- ------------------------------ -- Check that the given URI reports the HTTP status. -- ------------------------------ procedure Check_Security (T : in out Test; URI : in String; Result : in Natural) is Ctx : ASF.Servlets.Servlet_Registry; S1 : aliased ASF.Servlets.Tests.Test_Servlet1; F1 : aliased ASF.Security.Filters.Auth_Filter; Sec : aliased Policies.Policy_Manager (Max_Policies => 10); begin F1.Set_Permission_Manager (Sec'Unchecked_Access); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Filter ("Security", F1'Unchecked_Access); Sec.Add_Policy (new Policies.URLs.URL_Policy); Sec.Read_Policy (Util.Tests.Get_Path ("regtests/files/permissions/simple-policy.xml")); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Filter_Mapping (Pattern => "*.jsf", Name => "Security"); Ctx.Start; declare Dispatcher : constant ASF.Servlets.Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI & ".jsf"); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; begin Req.Set_Request_URI ("/admin/test"); Req.Set_Method ("GET"); ASF.Servlets.Forward (Dispatcher, Req, Resp); Assert_Equals (T, Result, Resp.Get_Status, "Invalid status"); end; end Check_Security; -- ------------------------------ -- Test the security filter granting permission for a given URI. -- ------------------------------ procedure Test_Security_Filter (T : in out Test) is begin T.Check_Security ("/admin/test", ASF.Responses.SC_UNAUTHORIZED); end Test_Security_Filter; -- ------------------------------ -- Test the security filter grants access to anonymous allowed pages. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Check_Security ("/view", ASF.Responses.SC_OK); end Test_Anonymous_Access; package Caller is new Util.Test_Caller (Test, "Security"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Security.Filters.Auth_Filter (deny)", Test_Security_Filter'Access); Caller.Add_Test (Suite, "Test ASF.Security.Filters.Auth_Filter (grant)", Test_Anonymous_Access'Access); end Add_Tests; end ASF.Security.Tests;
Call the Start procedure so that the servlet filters are installed
Call the Start procedure so that the servlet filters are installed
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ec6d3c64501f44fa86daf23804786a6f6455c92b
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- 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.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- Destroy the frame tree recursively. procedure Destroy (Tree : in out Frame_Ptr) is F : Frame_Ptr; begin -- Destroy its children recursively. while Tree.Children /= null loop F := Tree.Children; Destroy (F); end loop; -- Unlink from parent list. if Tree.Parent /= null then F := Tree.Parent.Children; if F = Tree then Tree.Parent.Children := Tree.Next; else while F /= null and F.Next /= Tree loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Tree.Next; end if; end if; Free (Tree); end Destroy; -- Release the frame when its reference is no longer necessary. procedure Release (F : in Frame_Ptr) is Current : Frame_Ptr := F; begin -- Scan the fram until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Ptr := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- 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.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and F.Next /= Frame loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Frame.Next; end if; end if; Free (Frame); end Destroy; -- Release the frame when its reference is no longer necessary. procedure Release (F : in Frame_Ptr) is Current : Frame_Ptr := F; begin -- Scan the fram until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Ptr := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
Refactor Destroy operation
Refactor Destroy operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8cee29a681fb9c589535f7a0105553806903287b
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : Natural := Value'Last; Pad : Natural := 0; Fill : Natural := 0; begin case Justify is when J_LEFT => if Value'Length < Size then Pad := Size - Value'Length; else Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Fill := Size - Value'Length; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; Fill := Size - Value'Length - Pad; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); end if; Ada.Text_IO.Put (Value (Start .. Last)); if Fill > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad + Fill + Last - Start)); else Ada.Text_IO.Put (" "); end if; end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text 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. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : Natural := Value'Last; Pad : Natural := 0; Fill : Natural := 0; begin case Justify is when J_LEFT => if Value'Length < Size then Fill := Size - Value'Length; else Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; Fill := Size - Value'Length - Pad; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); end if; Ada.Text_IO.Put (Value (Start .. Last)); if Fill > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad + Fill + Last - Start)); else Ada.Text_IO.Put (" "); end if; end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Fix the J_LEFT and J_RIGHT justifications that were inverted
Fix the J_LEFT and J_RIGHT justifications that were inverted
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9da62adbca574c88e21fadf70914114b7f405177
mat/src/memory/mat-memory.ads
mat/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Ptr; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); -- Memory allocation objects are stored in an AVL tree sorted -- on the memory slot address. -- -- subtype Allocation_Map is Allocation_Maps.Map; -- -- subtype Allocation_Ref is Allocation_AVL.Iterator; -- -- Type representing a reference to a memory allocation slot. -- -- use Allocation_AVL; -- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref); -- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees; -- package Allocation_Ref_AVL is -- new Allocation_Ref_Trees.AVL (Key => Target_Addr, -- Storage => Global_Heap.Storage); -- -- Tree of references to memory allocation objects. -- -- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree; -- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator; private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Ptr; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); -- Memory allocation objects are stored in an AVL tree sorted -- on the memory slot address. -- subtype Allocation_Map is Allocation_Maps.Map; -- -- subtype Allocation_Ref is Allocation_AVL.Iterator; -- -- Type representing a reference to a memory allocation slot. -- -- use Allocation_AVL; -- package Allocation_Ref_Containers is new BC.Containers (Allocation_Ref); -- package Allocation_Ref_Trees is new Allocation_Ref_Containers.Trees; -- package Allocation_Ref_AVL is -- new Allocation_Ref_Trees.AVL (Key => Target_Addr, -- Storage => Global_Heap.Storage); -- -- Tree of references to memory allocation objects. -- -- subtype Allocation_Ref_Map is Allocation_Ref_AVL.AVL_Tree; -- subtype Allocation_Ref_Ref is Allocation_Ref_AVL.Iterator; private end MAT.Memory;
Define Allocation_Map
Define Allocation_Map
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1dc95bb4336003707cbdacc7c94f20d0fb7a9684
regtests/ado-objects-tests.ads
regtests/ado-objects-tests.ads
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Objects.Tests is type Test is new Util.Tests.Test with null record; procedure Test_Key (T : in out Test); procedure Test_Object_Ref (T : in out Test); procedure Test_Create_Object (T : in out Test); procedure Test_Delete_Object (T : in out Test); -- Test Is_Inserted and Is_Null procedure Test_Is_Inserted (T : in out Test); -- Add the tests in the test suite procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); end ADO.Objects.Tests;
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Objects.Tests is type Test is new Util.Tests.Test with null record; procedure Test_Key (T : in out Test); procedure Test_Object_Ref (T : in out Test); procedure Test_Create_Object (T : in out Test); procedure Test_Delete_Object (T : in out Test); -- Test Is_Inserted and Is_Null procedure Test_Is_Inserted (T : in out Test); -- Test object creation/update/load with string as key. procedure Test_String_Key (T : in out Test); -- Add the tests in the test suite procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); end ADO.Objects.Tests;
Declare Test_String_Key procedure
Declare Test_String_Key procedure
Ada
apache-2.0
stcarrez/ada-ado
fdd736f163dc4171df927ab8958869fa3dd562a9
regtests/util-locales-tests.ads
regtests/util-locales-tests.ads
----------------------------------------------------------------------- -- locales.tests -- Unit tests for Locales -- 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.Locales.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Get_Locale (T : in out Test); procedure Test_Hash_Locale (T : in out Test); procedure Test_Compare_Locale (T : in out Test); procedure Test_Get_Locales (T : in out Test); end Util.Locales.Tests;
----------------------------------------------------------------------- -- util-locales-tests -- Unit tests for Locales -- Copyright (C) 2009, 2010, 2011, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Locales.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Get_Locale (T : in out Test); procedure Test_Hash_Locale (T : in out Test); procedure Test_Compare_Locale (T : in out Test); procedure Test_Get_Locales (T : in out Test); procedure Test_Null_Locale (T : in out Test); end Util.Locales.Tests;
Declare the new Test_Null_Locale procedure
Declare the new Test_Null_Locale procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f0a0bff6db9c512a3dee2b174215e41d29c2bb22
src/babel_main.adb
src/babel_main.adb
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;
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 (""); Store.Set_Buffers (Buffers'Unchecked_Access); Local.Set_Buffers (Buffers'Unchecked_Access); 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;
Set the buffer pool for the local stores
Set the buffer pool for the local stores
Ada
apache-2.0
stcarrez/babel
e76c1f31d2362e3f947a465b1ca5ff9e716cf79c
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is abstract tagged limited private; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is abstract new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is abstract tagged limited private; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is abstract new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Add a Permission_Index_Set to the Application record Declare the Has_Permission procedure
Add a Permission_Index_Set to the Application record Declare the Has_Permission procedure
Ada
apache-2.0
stcarrez/ada-security
5ab82ea802fada626a628fb7c481eaa84797e75a
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- 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. -- -- <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> -- -- 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. -- -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- === 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: -- -- <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> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Document the role based policy
Document the role based policy
Ada
apache-2.0
Letractively/ada-security
a29299f4e5cbc0e3c28a97bae92dd6bbf768394b
src/http/util-http-clients.ads
src/http/util-http-clients.ads
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- 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; -- 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; -- 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); -- 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); -- 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)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- 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; -- 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; -- 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); -- 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); -- 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)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- 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); -- Set the timeout for the connection. procedure Set_Timeout (Request : in out Client; Timeout : in Duration); -- 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); -- 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); -- Execute an http PUT 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 Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); -- Execute a http DELETE request on the given URL. procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Put (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Delete (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; -- Set the timeout for the connection. procedure Set_Timeout (Manager : in Http_Manager; Http : in Client'Class; Timeout : in Duration) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is limited new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is limited new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Streams.Texts; with Util.Serialize.IO.Form; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with private; procedure Initialize (Form : in out Form_Data; Size : in Positive); -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- 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; -- 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; -- 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); -- 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); -- 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)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- 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; -- 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; -- 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); -- 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); -- 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)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- 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); -- Set the timeout for the connection. procedure Set_Timeout (Request : in out Client; Timeout : in Duration); -- 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); -- 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); procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class); -- Execute an http PUT 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 Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); -- Execute a http DELETE request on the given URL. procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Put (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Delete (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; -- Set the timeout for the connection. procedure Set_Timeout (Manager : in Http_Manager; Http : in Client'Class; Timeout : in Duration) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is limited new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is limited new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with record Buffer : aliased Util.Streams.Texts.Print_Stream; end record; end Util.Http.Clients;
Declare the Form_Data type to help in serializing some form parameters Add a Post procedure that accepts a Form_Data object
Declare the Form_Data type to help in serializing some form parameters Add a Post procedure that accepts a Form_Data object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
810d5caf0beb6654f172d73c4fda8f5697d5e11c
tools/upnp-ssdp.adb
tools/upnp-ssdp.adb
----------------------------------------------------------------------- -- upnp-ssdp -- UPnP SSDP operations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Calendar; with Util.Log.Loggers; package body UPnP.SSDP is 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 ("UPnP.SSDP"); Group : constant String := "239.255.255.250"; procedure Send (Socket : in GNAT.Sockets.Socket_Type; Content : in String; To : access GNAT.Sockets.Sock_Addr_Type); -- ------------------------------ -- Initialize the SSDP scanner by opening the UDP socket. -- ------------------------------ procedure Initialize (Scanner : in out Scanner_Type) is Address : aliased GNAT.Sockets.Sock_Addr_Type; begin Log.Info ("Discovering gateways on the network"); Address.Addr := GNAT.Sockets.Any_Inet_Addr; GNAT.Sockets.Create_Socket (Scanner.Socket, GNAT.Sockets.Family_Inet, GNAT.Sockets.Socket_Datagram); GNAT.Sockets.Bind_Socket (Scanner.Socket, Address); GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level, (GNAT.Sockets.Add_Membership, GNAT.Sockets.Inet_Addr (Group), GNAT.Sockets.Any_Inet_Addr)); end Initialize; procedure Send (Socket : in GNAT.Sockets.Socket_Type; Content : in String; To : access GNAT.Sockets.Sock_Addr_Type) is Last : Ada.Streams.Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (1 .. Content'Length); for Buf'Address use Content'Address; pragma Import (Ada, Buf); pragma Unreferenced (Last); begin GNAT.Sockets.Send_Socket (Socket, Buf, Last, To); end Send; -- ------------------------------ -- Send the SSDP discovery UDP packet on the UPnP multicast group 239.255.255.250. -- Set the "ST" header to the given target. The UDP packet is sent on each interface -- whose IP address is defined in the set <tt>IPs</tt>. -- ------------------------------ procedure Send_Discovery (Scanner : in out Scanner_Type; Target : in String; IPs : in Util.Strings.Sets.Set) is Address : aliased GNAT.Sockets.Sock_Addr_Type; begin Address.Addr := GNAT.Sockets.Inet_Addr (Group); Address.Port := 1900; for IP of IPs loop GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level, (GNAT.Sockets.Multicast_If, GNAT.Sockets.Inet_Addr (IP))); Log.Debug ("Sending SSDP search for IGD device from {0}", IP); Send (Scanner.Socket, "M-SEARCH * HTTP/1.1" & ASCII.CR & ASCII.LF & "HOST: 239.255.255.250:1900" & ASCII.CR & ASCII.LF & "ST: " & Target & ASCII.CR & ASCII.LF & "MAN: ""ssdp:discover""" & ASCII.CR & ASCII.LF & "MX: 2" & ASCII.CR & ASCII.LF, Address'Access); end loop; end Send_Discovery; procedure Receive (Socket : in GNAT.Sockets.Socket_Type; Target : in String; Desc : out Ada.Strings.Unbounded.Unbounded_String) is function Get_Line return String; Data : Ada.Streams.Stream_Element_Array (0 .. 1500); Last : Ada.Streams.Stream_Element_Offset; Pos : Ada.Streams.Stream_Element_Offset := Data'First; function Get_Line return String is First : constant Ada.Streams.Stream_Element_Offset := Pos; begin while Pos <= Last loop if Data (Pos) = 16#0D# and then Pos + 1 <= Last and then Data (Pos + 1) = 16#0A# then declare Result : String (1 .. Natural (Pos - First)); P : Natural := 1; begin for I in First .. Pos - 1 loop Result (P) := Character'Val (Data (I)); P := P + 1; end loop; Log.Debug ("L: {0}", Result); Pos := Pos + 2; return Result; end; end if; Pos := Pos + 1; end loop; return ""; end Get_Line; begin Desc := Ada.Strings.Unbounded.To_Unbounded_String (""); GNAT.Sockets.Receive_Socket (Socket, Data, Last); if Get_Line /= "HTTP/1.1 200 OK" then Log.Debug ("Receive a non HTTP/1.1 response"); return; end if; loop declare Line : constant String := Get_Line; Pos : constant Natural := Util.Strings.Index (Line, ':'); Pos2 : Natural := Pos + 1; begin exit when Pos = 0; while Pos2 < Line'Last and then Line (Pos2) = ' ' loop Pos2 := Pos2 + 1; end loop; if Line (1 .. Pos) = "ST:" then if Line (Pos2 .. Line'Last) /= Target then return; end if; elsif Line (1 .. Pos) = "LOCATION:" then Desc := Ada.Strings.Unbounded.To_Unbounded_String (Line (Pos2 .. Line'Last)); Log.Debug ("Found a IGD device: {0}", Ada.Strings.Unbounded.To_String (Desc)); return; end if; end; end loop; exception when E : others => Log.Error ("Exception received", E); end Receive; -- ------------------------------ -- Receive the UPnP SSDP discovery messages for the given target. -- Call the <tt>Process</tt> procedure for each of them. The <tt>Desc</tt> parameter -- represents the UPnP location header which gives the UPnP XML root descriptor. -- Wait at most the given time. -- ------------------------------ procedure Discover (Scanner : in out Scanner_Type; Target : in String; Process : not null access procedure (Desc : in String); Wait : in Duration) is use type Ada.Calendar.Time; use type GNAT.Sockets.Selector_Status; Sel : GNAT.Sockets.Selector_Type; Rset : GNAT.Sockets.Socket_Set_Type; Wset : GNAT.Sockets.Socket_Set_Type; Status : GNAT.Sockets.Selector_Status; Desc : Ada.Strings.Unbounded.Unbounded_String; Deadline : constant Ada.Calendar.Time := Ada.Calendar.Clock + Wait; Remain : Duration; begin GNAT.Sockets.Create_Selector (Sel); loop GNAT.Sockets.Empty (Rset); GNAT.Sockets.Empty (Wset); GNAT.Sockets.Set (Rset, Scanner.Socket); Remain := Deadline - Ada.Calendar.Clock; exit when Remain < 0.0; GNAT.Sockets.Check_Selector (Selector => Sel, R_Socket_Set => Rset, W_Socket_Set => Wset, Status => Status, Timeout => Remain); exit when Status = GNAT.Sockets.Expired; Receive (Scanner.Socket, Target, Desc); declare URI : constant String := Ada.Strings.Unbounded.To_String (Desc); Pos : constant Natural := Util.Strings.Index (URI, ':'); begin if Pos > 0 and URI (URI'First .. Pos + 2) = "http://" then Process (URI); end if; end; end loop; end Discover; -- ------------------------------ -- Release the socket. -- ------------------------------ overriding procedure Finalize (Scanner : in out Scanner_Type) is use type GNAT.Sockets.Socket_Type; begin if Scanner.Socket /= GNAT.Sockets.No_Socket then GNAT.Sockets.Close_Socket (Scanner.Socket); end if; end Finalize; end UPnP.SSDP;
----------------------------------------------------------------------- -- upnp-ssdp -- UPnP SSDP operations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Calendar; with System; with Interfaces.C.Strings; with Util.Log.Loggers; package body UPnP.SSDP is 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 ("UPnP.SSDP"); Group : constant String := "239.255.255.250"; type Sockaddr is record Sa_Family : Interfaces.C.unsigned_short; Sa_Port : Interfaces.C.unsigned_short; Sa_Addr : aliased Interfaces.C.char_array (1 .. 8); end record; pragma Convention (C, Sockaddr); type If_Address; type If_Address_Access is access all If_Address; type If_Address is record Ifa_Next : If_Address_Access; Ifa_Name : Interfaces.C.Strings.chars_ptr; Ifa_Flags : Interfaces.C.unsigned; Ifa_Addr : access Sockaddr; end record; pragma Convention (C, If_Address); function Sys_getifaddrs (ifap : access If_Address_Access) return Interfaces.C.int; pragma Import (C, Sys_getifaddrs, "getifaddrs"); procedure Sys_freeifaddrs (ifap : If_Address_Access); pragma Import (C, Sys_freeifaddrs, "freeifaddrs"); function Sys_Inet_Ntop (Af : in Interfaces.C.unsigned_short; Addr : System.Address; Dst : in Interfaces.C.Strings.chars_ptr; Size : in Interfaces.C.int) return Interfaces.C.Strings.chars_ptr; pragma Import (C, Sys_Inet_Ntop, "inet_ntop"); procedure Send (Socket : in GNAT.Sockets.Socket_Type; Content : in String; To : access GNAT.Sockets.Sock_Addr_Type); procedure Receive (Socket : in GNAT.Sockets.Socket_Type; Target : in String; Desc : out Ada.Strings.Unbounded.Unbounded_String); -- ------------------------------ -- Initialize the SSDP scanner by opening the UDP socket. -- ------------------------------ procedure Initialize (Scanner : in out Scanner_Type) is Address : aliased GNAT.Sockets.Sock_Addr_Type; begin Log.Info ("Discovering gateways on the network"); Address.Addr := GNAT.Sockets.Any_Inet_Addr; GNAT.Sockets.Create_Socket (Scanner.Socket, GNAT.Sockets.Family_Inet, GNAT.Sockets.Socket_Datagram); GNAT.Sockets.Bind_Socket (Scanner.Socket, Address); GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level, (GNAT.Sockets.Add_Membership, GNAT.Sockets.Inet_Addr (Group), GNAT.Sockets.Any_Inet_Addr)); end Initialize; -- ------------------------------ -- Find the IPv4 addresses of the network interfaces. -- ------------------------------ procedure Find_IPv4_Addresses (Scanner : in out Scanner_Type; IPs : out Util.Strings.Sets.Set) is pragma Unreferenced (Scanner); use type Interfaces.C.int; use type Interfaces.C.Strings.chars_ptr; Iflist : aliased If_Address_Access; Ifp : If_Address_Access; R : Interfaces.C.Strings.chars_ptr; begin if Sys_getifaddrs (Iflist'Access) = 0 then R := Interfaces.C.Strings.New_String ("xxx.xxx.xxx.xxx.xxx"); Ifp := Iflist; while Ifp /= null loop if Sys_Inet_Ntop (Ifp.Ifa_Addr.Sa_Family, Ifp.Ifa_Addr.Sa_Addr'Address, R, 17) /= Interfaces.C.Strings.Null_Ptr then Log.Debug ("Found interface: {0} - IP {1}", Interfaces.C.Strings.Value (Ifp.Ifa_Name), Interfaces.C.Strings.Value (R)); if Interfaces.C.Strings.Value (R) /= "::" then IPs.Include (Interfaces.C.Strings.Value (R)); end if; end if; Ifp := Ifp.Ifa_Next; end loop; Interfaces.C.Strings.Free (R); Sys_freeifaddrs (Iflist); end if; end Find_IPv4_Addresses; procedure Send (Socket : in GNAT.Sockets.Socket_Type; Content : in String; To : access GNAT.Sockets.Sock_Addr_Type) is Last : Ada.Streams.Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (1 .. Content'Length); for Buf'Address use Content'Address; pragma Import (Ada, Buf); pragma Unreferenced (Last); begin GNAT.Sockets.Send_Socket (Socket, Buf, Last, To); end Send; -- ------------------------------ -- Send the SSDP discovery UDP packet on the UPnP multicast group 239.255.255.250. -- Set the "ST" header to the given target. The UDP packet is sent on each interface -- whose IP address is defined in the set <tt>IPs</tt>. -- ------------------------------ procedure Send_Discovery (Scanner : in out Scanner_Type; Target : in String; IPs : in Util.Strings.Sets.Set) is Address : aliased GNAT.Sockets.Sock_Addr_Type; begin Address.Addr := GNAT.Sockets.Inet_Addr (Group); Address.Port := 1900; for IP of IPs loop GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level, (GNAT.Sockets.Multicast_If, GNAT.Sockets.Inet_Addr (IP))); Log.Debug ("Sending SSDP search for IGD device from {0}", IP); Send (Scanner.Socket, "M-SEARCH * HTTP/1.1" & ASCII.CR & ASCII.LF & "HOST: 239.255.255.250:1900" & ASCII.CR & ASCII.LF & "ST: " & Target & ASCII.CR & ASCII.LF & "MAN: ""ssdp:discover""" & ASCII.CR & ASCII.LF & "MX: 2" & ASCII.CR & ASCII.LF, Address'Access); end loop; end Send_Discovery; procedure Receive (Socket : in GNAT.Sockets.Socket_Type; Target : in String; Desc : out Ada.Strings.Unbounded.Unbounded_String) is function Get_Line return String; Data : Ada.Streams.Stream_Element_Array (0 .. 1500); Last : Ada.Streams.Stream_Element_Offset; Pos : Ada.Streams.Stream_Element_Offset := Data'First; function Get_Line return String is First : constant Ada.Streams.Stream_Element_Offset := Pos; begin while Pos <= Last loop if Data (Pos) = 16#0D# and then Pos + 1 <= Last and then Data (Pos + 1) = 16#0A# then declare Result : String (1 .. Natural (Pos - First)); P : Natural := 1; begin for I in First .. Pos - 1 loop Result (P) := Character'Val (Data (I)); P := P + 1; end loop; Log.Debug ("L: {0}", Result); Pos := Pos + 2; return Result; end; end if; Pos := Pos + 1; end loop; return ""; end Get_Line; begin Desc := Ada.Strings.Unbounded.To_Unbounded_String (""); GNAT.Sockets.Receive_Socket (Socket, Data, Last); if Get_Line /= "HTTP/1.1 200 OK" then Log.Debug ("Receive a non HTTP/1.1 response"); return; end if; loop declare Line : constant String := Get_Line; Pos : constant Natural := Util.Strings.Index (Line, ':'); Pos2 : Natural := Pos + 1; begin exit when Pos = 0; while Pos2 < Line'Last and then Line (Pos2) = ' ' loop Pos2 := Pos2 + 1; end loop; if Line (1 .. Pos) = "ST:" then if Line (Pos2 .. Line'Last) /= Target then return; end if; elsif Line (1 .. Pos) = "LOCATION:" then Desc := Ada.Strings.Unbounded.To_Unbounded_String (Line (Pos2 .. Line'Last)); Log.Debug ("Found a IGD device: {0}", Ada.Strings.Unbounded.To_String (Desc)); return; end if; end; end loop; exception when E : others => Log.Error ("Exception received", E); end Receive; -- ------------------------------ -- Receive the UPnP SSDP discovery messages for the given target. -- Call the <tt>Process</tt> procedure for each of them. The <tt>Desc</tt> parameter -- represents the UPnP location header which gives the UPnP XML root descriptor. -- Wait at most the given time. -- ------------------------------ procedure Discover (Scanner : in out Scanner_Type; Target : in String; Process : not null access procedure (Desc : in String); Wait : in Duration) is use type Ada.Calendar.Time; use type GNAT.Sockets.Selector_Status; Sel : GNAT.Sockets.Selector_Type; Rset : GNAT.Sockets.Socket_Set_Type; Wset : GNAT.Sockets.Socket_Set_Type; Status : GNAT.Sockets.Selector_Status; Desc : Ada.Strings.Unbounded.Unbounded_String; Deadline : constant Ada.Calendar.Time := Ada.Calendar.Clock + Wait; Remain : Duration; begin GNAT.Sockets.Create_Selector (Sel); loop GNAT.Sockets.Empty (Rset); GNAT.Sockets.Empty (Wset); GNAT.Sockets.Set (Rset, Scanner.Socket); Remain := Deadline - Ada.Calendar.Clock; exit when Remain < 0.0; GNAT.Sockets.Check_Selector (Selector => Sel, R_Socket_Set => Rset, W_Socket_Set => Wset, Status => Status, Timeout => Remain); exit when Status = GNAT.Sockets.Expired; Receive (Scanner.Socket, Target, Desc); declare URI : constant String := Ada.Strings.Unbounded.To_String (Desc); Pos : constant Natural := Util.Strings.Index (URI, ':'); begin if Pos > 0 and URI (URI'First .. Pos + 2) = "http://" then Process (URI); end if; end; end loop; end Discover; -- ------------------------------ -- Release the socket. -- ------------------------------ overriding procedure Finalize (Scanner : in out Scanner_Type) is use type GNAT.Sockets.Socket_Type; begin if Scanner.Socket /= GNAT.Sockets.No_Socket then GNAT.Sockets.Close_Socket (Scanner.Socket); end if; end Finalize; end UPnP.SSDP;
Implement the Find_IPv4_Addresses by using the getifaddrs C API
Implement the Find_IPv4_Addresses by using the getifaddrs C API
Ada
apache-2.0
stcarrez/bbox-ada-api
5d6a408cf48c913461c5b1769349fed9afefa5cc
regtests/ado-datasets-tests.adb
regtests/ado-datasets-tests.adb
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 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.Test_Caller; with Regtests.Simple.Model; with Regtests.Statements.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.List (<sql> with null)", Test_List_Nullable'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; -- ------------------------------ -- Test dataset lists with null columns. -- ------------------------------ procedure Test_List_Nullable (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_SQL ("SELECT COUNT(*) FROM test_nullable_table"); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare Item : Regtests.Statements.Model.Nullable_Table_Ref; begin Item.Set_Bool_Value (False); if (I mod 2) = 0 then Item.Set_Int_Value (ADO.Nullable_Integer '(123, False)); end if; if (I mod 4) = 0 then Item.Set_Time_Value (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Item.Save (DB); end; end loop; DB.Commit; Query.Set_SQL ("SELECT * FROM test_nullable_table"); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List_Nullable; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
----------------------------------------------------------------------- -- ado-datasets-tests -- Test executing queries and using datasets -- Copyright (C) 2013, 2014, 2015, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Regtests.Simple.Model; with Regtests.Statements.Model; with ADO.Queries.Loaders; package body ADO.Datasets.Tests is package Caller is new Util.Test_Caller (Test, "ADO.Datasets"); package User_List_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/user-list.xml", Sha1 => ""); package User_List_Query is new ADO.Queries.Loaders.Query (Name => "user-list", File => User_List_Query_File.File'Access); package User_List_Count_Query is new ADO.Queries.Loaders.Query (Name => "user-list-count", File => User_List_Query_File.File'Access); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Datasets.List (from <sql>)", Test_List'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql>)", Test_Count'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.Get_Count (from <sql-count>)", Test_Count_Query'Access); Caller.Add_Test (Suite, "Test ADO.Datasets.List (<sql> with null)", Test_List_Nullable'Access); end Add_Tests; procedure Test_List (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare User : Regtests.Simple.Model.User_Ref; begin User.Set_Name ("John " & Integer'Image (I)); User.Set_Select_Name ("test-list"); User.Set_Value (ADO.Identifier (I)); User.Save (DB); end; end loop; DB.Commit; Query.Set_Query (User_List_Query.Query'Access); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List; -- ------------------------------ -- Test dataset lists with null columns. -- ------------------------------ procedure Test_List_Nullable (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; Data : ADO.Datasets.Dataset; begin Query.Set_SQL ("SELECT COUNT(*) FROM test_nullable_table"); Count := ADO.Datasets.Get_Count (DB, Query); for I in 1 .. 100 loop declare Item : Regtests.Statements.Model.Nullable_Table_Ref; begin Item.Set_Bool_Value ((Value => False, Is_Null => False)); if (I mod 2) = 0 then Item.Set_Int_Value (ADO.Nullable_Integer '(123, False)); end if; if (I mod 4) = 0 then Item.Set_Time_Value (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Item.Save (DB); end; end loop; DB.Commit; Query.Set_SQL ("SELECT * FROM test_nullable_table"); ADO.Datasets.List (Data, DB, Query); Util.Tests.Assert_Equals (T, 100 + Count, Data.Get_Count, "Invalid dataset size"); end Test_List_Nullable; procedure Test_Count (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Query (User_List_Count_Query.Query'Access); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count; procedure Test_Count_Query (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Query : ADO.Queries.Context; Count : Natural; begin Query.Set_Count_Query (User_List_Query.Query'Access); Query.Bind_Param ("filter", String '("test-list")); Count := ADO.Datasets.Get_Count (DB, Query); T.Assert (Count > 0, "The ADO.Datasets.Get_Count query should return a positive count"); end Test_Count_Query; end ADO.Datasets.Tests;
Update the test for boolean value
Update the test for boolean value
Ada
apache-2.0
stcarrez/ada-ado
e6704681d5049b3a7672bbb7d108ba6691d34472
regtests/asf-sessions-tests.adb
regtests/asf-sessions-tests.adb
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- 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 AUnit.Test_Caller; with Ada.Text_IO; with ASF.Sessions.Factory; with Ada.Calendar; with Util.Tests; with Util.Measures; with EL.Objects; package body ASF.Sessions.Tests is use Util.Tests; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Session (T : in out Test) is F : ASF.Sessions.Factory.Session_Factory; S : ASF.Sessions.Session; St : Util.Measures.Stamp; begin for I in 1 .. 10 loop F.Create_Session (S); end loop; Util.Measures.Report (St, "10 Session create"); for I in 1 .. 100 loop F.Create_Session (S); T.Assert (S.Is_Valid, "Session should be valid"); T.Assert (S.Get_Id'Length = 32, "Session id has an invalid length"); Ada.Text_IO.Put_Line ("ID=" & S.Get_Id); declare S2 : ASF.Sessions.Session; begin F.Find_Session (Id => S.Get_Id, Result => S2); T.Assert (S2.Is_Valid, "Session was not found"); Assert_Equals (T, S.Get_Id, S2.Get_Id, "Invalid session id"); end; end loop; end Test_Create_Session; -- ------------------------------ -- Tests on an empty session object. -- ------------------------------ procedure Test_Empty_Session (T : in out Test) is S : ASF.Sessions.Session; begin T.Assert (not S.Is_Valid, "Session should be invalid"); S.Invalidate; T.Assert (not S.Is_Valid, "Session should be invalid"); end Test_Empty_Session; procedure Test_Session_Attributes (T : in out Test) is F : ASF.Sessions.Factory.Session_Factory; S : ASF.Sessions.Session; begin F.Create_Session (S); S.Set_Attribute ("a1", EL.Objects.To_Object (Integer (234))); S.Set_Attribute ("a2", EL.Objects.To_Object (String '("name"))); declare Value : EL.Objects.Object := S.Get_Attribute ("a1"); begin Assert_Equals (T, "234", EL.Objects.To_String (Value), "Invalid attribute a1"); end; end Test_Session_Attributes; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Factory.Create_Session", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Factory.Find_Session", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Get_Id", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Is_Valid", Test_Empty_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Set_Attribute", Test_Session_Attributes'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Get_Attribute", Test_Session_Attributes'Access)); end Add_Tests; end ASF.Sessions.Tests;
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- 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 AUnit.Test_Caller; with Ada.Text_IO; with ASF.Sessions.Factory; with Ada.Calendar; with Util.Tests; with Util.Measures; with EL.Objects; package body ASF.Sessions.Tests is use Util.Tests; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Session (T : in out Test) is F : ASF.Sessions.Factory.Session_Factory; S : ASF.Sessions.Session; St : Util.Measures.Stamp; begin for I in 1 .. 10 loop F.Create_Session (S); end loop; Util.Measures.Report (St, "10 Session create"); for I in 1 .. 100 loop F.Create_Session (S); T.Assert (S.Is_Valid, "Session should be valid"); T.Assert (S.Get_Id'Length = 32, "Session id has an invalid length"); -- Ada.Text_IO.Put_Line ("ID=" & S.Get_Id); declare S2 : ASF.Sessions.Session; begin F.Find_Session (Id => S.Get_Id, Result => S2); T.Assert (S2.Is_Valid, "Session was not found"); Assert_Equals (T, S.Get_Id, S2.Get_Id, "Invalid session id"); end; end loop; end Test_Create_Session; -- ------------------------------ -- Tests on an empty session object. -- ------------------------------ procedure Test_Empty_Session (T : in out Test) is S : ASF.Sessions.Session; begin T.Assert (not S.Is_Valid, "Session should be invalid"); S.Invalidate; T.Assert (not S.Is_Valid, "Session should be invalid"); end Test_Empty_Session; procedure Test_Session_Attributes (T : in out Test) is F : ASF.Sessions.Factory.Session_Factory; S : ASF.Sessions.Session; begin F.Create_Session (S); S.Set_Attribute ("a1", EL.Objects.To_Object (Integer (234))); S.Set_Attribute ("a2", EL.Objects.To_Object (String '("name"))); declare Value : EL.Objects.Object := S.Get_Attribute ("a1"); begin Assert_Equals (T, "234", EL.Objects.To_String (Value), "Invalid attribute a1"); end; end Test_Session_Attributes; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Factory.Create_Session", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Factory.Find_Session", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Get_Id", Test_Create_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Is_Valid", Test_Empty_Session'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Set_Attribute", Test_Session_Attributes'Access)); Suite.Add_Test (Caller.Create ("Test ASF.Sessions.Get_Attribute", Test_Session_Attributes'Access)); end Add_Tests; end ASF.Sessions.Tests;
Remove dump of session ID
Remove dump of session ID
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
a9e6f48a53ea4f6037a7e85f58749bff8e8211f9
regtests/wiki-parsers-tests.ads
regtests/wiki-parsers-tests.ads
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Wiki.Parsers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test bold rendering. procedure Test_Wiki_Bold (T : in out Test); -- Test italic rendering. procedure Test_Wiki_Italic (T : in out Test); -- Test various format rendering. procedure Test_Wiki_Formats (T : in out Test); -- Test heading rendering. procedure Test_Wiki_Section (T : in out Test); -- Test list rendering. procedure Test_Wiki_List (T : in out Test); -- Test link rendering. procedure Test_Wiki_Link (T : in out Test); -- Test quote rendering. procedure Test_Wiki_Quote (T : in out Test); -- Test line break rendering. procedure Test_Wiki_Line_Break (T : in out Test); -- Test image rendering. procedure Test_Wiki_Image (T : in out Test); -- Test preformatted rendering. procedure Test_Wiki_Preformatted (T : in out Test); -- Test the text renderer. procedure Test_Wiki_Text_Renderer (T : in out Test); end Wiki.Parsers.Tests;
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Wiki.Parsers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test bold rendering. procedure Test_Wiki_Bold (T : in out Test); -- Test italic rendering. procedure Test_Wiki_Italic (T : in out Test); -- Test various format rendering. procedure Test_Wiki_Formats (T : in out Test); -- Test heading rendering. procedure Test_Wiki_Section (T : in out Test); -- Test list rendering. procedure Test_Wiki_List (T : in out Test); -- Test link rendering. procedure Test_Wiki_Link (T : in out Test); -- Test quote rendering. procedure Test_Wiki_Quote (T : in out Test); -- Test line break rendering. procedure Test_Wiki_Line_Break (T : in out Test); -- Test image rendering. procedure Test_Wiki_Image (T : in out Test); -- Test preformatted rendering. procedure Test_Wiki_Preformatted (T : in out Test); -- Test the text renderer. procedure Test_Wiki_Text_Renderer (T : in out Test); -- Test the string parser with UTF-8 support. procedure Test_Wiki_UTF_8 (T : in out Test); end Wiki.Parsers.Tests;
Declare Test_Wiki_UTF_8 procedure
Declare Test_Wiki_UTF_8 procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ccba155e60bf22e615388aa09067cbcea16857ba
src/util-serialize-io.ads
src/util-serialize-io.ads
----------------------------------------------------------------------- -- 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 Ada.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Log.Loggers; with Util.Nullables; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Reader is limited interface; -- Start a document. procedure Start_Document (Stream : in out Reader) is null; -- Finish a document. procedure End_Document (Stream : in out Reader) is null; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is abstract; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is abstract; type Parser is abstract new Util.Log.Logging with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- 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); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- 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); private type Parser is abstract new Util.Log.Logging with record Error_Flag : Boolean := False; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; 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 Ada.Strings.Unbounded; with Ada.Calendar; with Util.Beans.Objects; with Util.Streams; with Util.Streams.Buffered; with Util.Log.Loggers; with Util.Nullables; package Util.Serialize.IO is Parse_Error : exception; -- ------------------------------ -- Output stream for serialization -- ------------------------------ -- The <b>Output_Stream</b> interface defines the abstract operations for -- the serialization framework to write objects on the stream according to -- a target format such as XML or JSON. type Output_Stream is limited interface and Util.Streams.Output_Stream; -- Start a document. procedure Start_Document (Stream : in out Output_Stream) is null; -- Finish a document. procedure End_Document (Stream : in out Output_Stream) is null; procedure Start_Entity (Stream : in out Output_Stream; Name : in String) is null; procedure End_Entity (Stream : in out Output_Stream; Name : in String) is null; -- Write the attribute name/value pair. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- Write the attribute with a null value. procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is abstract; procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write the entity value. procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String) is abstract; procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is abstract; procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is abstract; procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is abstract; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String); -- Write an entity with a null value. procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is abstract; procedure Start_Array (Stream : in out Output_Stream; Name : in String) is null; procedure End_Array (Stream : in out Output_Stream; Name : in String) is null; type Reader is limited interface; -- Start a document. procedure Start_Document (Stream : in out Reader) is null; -- Finish a document. procedure End_Document (Stream : in out Reader) is null; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is abstract; procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is abstract; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is abstract; type Parser is abstract new Util.Log.Logging with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is abstract; -- Read the file and parse it using the parser. procedure Parse (Handler : in out Parser; File : in String; Sink : in out Reader'Class); -- Parse the content string. procedure Parse_String (Handler : in out Parser; Content : in String; Sink : in out Reader'Class); -- Returns true if the <b>Parse</b> operation detected at least one error. function Has_Error (Handler : in Parser) return Boolean; -- 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); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- 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); private type Parser is abstract new Util.Log.Logging with record Error_Flag : Boolean := False; -- The file name to use when reporting errors. File : Ada.Strings.Unbounded.Unbounded_String; -- The logger which is used to report error messages when parsing an input file. Error_Logger : Util.Log.Loggers.Logger_Access := null; end record; end Util.Serialize.IO;
Declare Write_Null_Attribute and Write_Null_Entity to write an attribute or entity with a null value
Declare Write_Null_Attribute and Write_Null_Entity to write an attribute or entity with a null value
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f2e6e05d658d317375dee2c905f2ba1ad93c039f
src/lzma/util-encoders-lzma.adb
src/lzma/util-encoders-lzma.adb
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Action : Base.lzma_action := Base.LZMA_RUN; Result : Base.lzma_ret; Pos : Ada.Streams.Stream_Element_Offset := Data'First; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Pos)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Action); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
----------------------------------------------------------------------- -- util-encoders-lzma -- LZMA compression and decompression -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; package body Util.Encoders.Lzma is use type Interfaces.C.size_t; use type Ada.Streams.Stream_Element_Offset; use type Base.lzma_ret; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Compress the binary input stream represented by <b>Data</b> by using -- the LZMA compression into the output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Compress; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := Data (Data'First)'Unrestricted_Access; E.Stream.avail_in := Interfaces.C.size_t (Data'Length); loop Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if E.Stream.avail_out = 0 or E.Stream.avail_in = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; Encoded := Data'First + Data'Length - Offset (E.Stream.avail_in); return; end if; exit when Result /= Base.LZMA_OK; end loop; end Transform; -- ------------------------------ -- Finish compression of the input array. -- ------------------------------ overriding procedure Finish (E : in out Compress; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin E.Stream.next_out := Into (Into'First)'Unchecked_Access; E.Stream.avail_out := Into'Length; E.Stream.next_in := null; E.Stream.avail_in := 0; Result := Base.lzma_code (E.Stream'Unchecked_Access, Base.LZMA_FINISH); Last := Into'First + Into'Length - Offset (E.Stream.avail_out) - 1; end Finish; overriding procedure Initialize (E : in out Compress) is Result : Base.lzma_ret; pragma Unreferenced (Result); begin Result := Container.lzma_easy_encoder (E.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); end Initialize; overriding procedure Finalize (E : in out Compress) is begin Base.lzma_end (E.Stream'Unchecked_Access); end Finalize; end Util.Encoders.Lzma;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e9c1b48a7a5dc9a86083e3197a73d932a6ae8962
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- 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. -- -- <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> -- -- 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. package Security.Policies.Roles is -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- 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. -- -- <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> -- -- 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. package Security.Policies.Roles is -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- 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); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Rename Set_Reader_Config into Prepare_Config
Rename Set_Reader_Config into Prepare_Config
Ada
apache-2.0
Letractively/ada-security
63bf3a1bfda9a353204f44a0d75f554148af2da8
Ada/Benchmark/src/main.adb
Ada/Benchmark/src/main.adb
with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar; use Ada.Calendar; with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Fibonacci; with Perfect_Number; with Primes; procedure Main is package Fib renames Fibonacci; package Pn renames Perfect_Number; procedure Put_Elapsed (Tic : Time; Toc : Time := Clock) is begin Put_Line (" elapsed time: " & Duration'Image(Toc - Tic) & "s"); end Put_Elapsed; -- overload Img function for string representatin of result data function Img (X : Natural) return String renames Natural'Image; function Img (X : Big_Natural) return String renames Fib.Big_Natural_Image; function Img (X : Pn.Pn_Vectors.Vector) return String is Res : Unbounded_String := Null_Unbounded_String; begin Res := Res & "["; for E of X loop Res := Res & Img (E) & ","; end loop; Res := Res & "]"; return To_String (Res); end Img; function Img (X : Primes.Prime_Vectors.Vector) return String is Res : Unbounded_String := Null_Unbounded_String; begin Res := Res & "["; for E of X loop Res := Res & Img (E) & ","; end loop; Res := Res & "]"; return To_String (Res); end Img; Tic : Time; begin Put_Line ("Benchmark"); Put_Line ("========="); New_Line; Put_Line ("Fibonacci Numbers"); Put_Line ("-----------------"); Tic := Clock; Put ("Fib_Naive (35) = " & Img (Fib.Fib_Naive (35))); Put_Elapsed (Tic); Tic := Clock; Put ("Fib_Iter (1000) = " & Img (Fib.Fib_Iter (1000))); Put_Elapsed (Tic); Tic := Clock; Put ("Fib_Recur (1000) = " & Img (Fib.Fib_Recur (1000))); Put_Elapsed (Tic); New_Line; Put_Line ("Perfect Numbers"); Put_Line ("---------------"); Tic := Clock; Put ("Perfect_Numbers (10000) = " & Img (Pn.Get_Perfect_Numbers (10000))); Put_Elapsed (Tic); New_line; Put_Line ("Prime Numbers"); Put_Line ("-------------"); Tic := Clock; Put ("Get_Primes (10000): (" & Img (Primes.Get_Primes (10_000)) & ")"); Put_Elapsed (Tic); Tic := Clock; -- FIXME: Provide Img overload for Primes.Prime_Vectors_Big.Vector --Put ("Get_Primes (10000): (" & Img (Primes.Get_Primes (To_Big_Integer (10_000))) & ")"); Put_Elapsed (Tic); New_Line; end Main;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar; use Ada.Calendar; with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Fibonacci; with Perfect_Number; with Primes; procedure Main is package Fib renames Fibonacci; package Pn renames Perfect_Number; procedure Put_Elapsed (Tic : Time; Toc : Time := Clock) is begin Put_Line (" elapsed time: " & Duration'Image(Toc - Tic) & "s"); end Put_Elapsed; -- overload Img function for string representatin of result data function Img (X : Natural) return String renames Natural'Image; function Img (X : Big_Natural) return String renames Fib.Big_Natural_Image; function Img (X : Pn.Pn_Vectors.Vector) return String is Res : Unbounded_String := Null_Unbounded_String; begin Res := Res & "["; for E of X loop Res := Res & Img (E) & ","; end loop; Res := Res & "]"; return To_String (Res); end Img; function Img (X : Primes.Prime_Vectors.Vector) return String is Res : Unbounded_String := Null_Unbounded_String; begin Res := Res & "["; for E of X loop Res := Res & Img (E) & ","; end loop; Res := Res & "]"; return To_String (Res); end Img; function Img (X : Primes.Big_Prime_Vectors.Vector) return String is Res : Unbounded_String := Null_Unbounded_String; begin Res := Res & "["; for E of X loop Res := Res & Img (E) & ","; end loop; Res := Res & "]"; return To_String (Res); end Img; Tic : Time; begin Put_Line ("Benchmark"); Put_Line ("========="); New_Line; Put_Line ("Fibonacci Numbers"); Put_Line ("-----------------"); Tic := Clock; Put ("Fib_Naive (35) = " & Img (Fib.Fib_Naive (35))); Put_Elapsed (Tic); Tic := Clock; Put ("Fib_Iter (1000) = " & Img (Fib.Fib_Iter (1000))); Put_Elapsed (Tic); Tic := Clock; Put ("Fib_Recur (1000) = " & Img (Fib.Fib_Recur (1000))); Put_Elapsed (Tic); New_Line; Put_Line ("Perfect Numbers"); Put_Line ("---------------"); Tic := Clock; Put ("Perfect_Numbers (10000) = " & Img (Pn.Get_Perfect_Numbers (10000))); Put_Elapsed (Tic); New_line; Put_Line ("Prime Numbers"); Put_Line ("-------------"); Tic := Clock; Put ("Get_Primes (10000): (" & Img (Primes.Get_Primes (10_000)) & ")"); Put_Elapsed (Tic); Tic := Clock; Put ("Get_Primes (10000): (" & Img (Primes.Get_Primes (To_Big_Integer (10_000))) & ")"); Put_Elapsed (Tic); New_Line; end Main;
add missing overload for Img ()
add missing overload for Img ()
Ada
mit
kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground
d7383801464f7d36262290cd187ce18332febf96
regtests/el-testsuite.adb
regtests/el-testsuite.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with EL.Expressions; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Expressions.Tests; with EL.Beans.Tests; with EL.Contexts.Tests; with EL.Utils.Tests; package body EL.Testsuite is use EL.Objects; -- ------------------------------ -- Test object integer -- ------------------------------ procedure Test_To_Object_Integer (T : in out Test) is begin declare Value : constant EL.Objects.Object := To_Object (Integer (1)); begin T.Assert (Condition => To_Integer (Value) = 1, Message => "Object.To_Integer: invalid integer returned"); T.Assert (Condition => To_Long_Integer (Value) = 1, Message => "Object.To_Long_Integer: invalid integer returned"); T.Assert (Condition => To_Boolean (Value), Message => "Object.To_Boolean: invalid return"); declare V2 : constant EL.Objects.Object := Value + To_Object (Long_Integer (100)); begin T.Assert (Condition => To_Integer (V2) = 101, Message => "To_Integer invalid after an add"); end; end; end Test_To_Object_Integer; -- ------------------------------ -- Test object integer -- ------------------------------ procedure Test_Expression (T : in out Test) is E : EL.Expressions.Expression; Value : Object; Ctx : EL.Contexts.Default.Default_Context; begin -- Positive number E := EL.Expressions.Create_Expression ("12345678901", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Long_Long_Integer (Value) = Long_Long_Integer (12345678901), Message => "[1] Expression result invalid: " & To_String (Value)); -- Negative number E := EL.Expressions.Create_Expression ("-10", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = -10, Message => "[2] Expression result invalid: " & To_String (Value)); -- Simple add E := EL.Expressions.Create_Expression ("#{1+1}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 2, Message => "[2.1] Expression result invalid: " & To_String (Value)); -- Constant expressions E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 492, Message => "[3] Expression result invalid: " & To_String (Value)); -- Constant expressions E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4 + (23? 10 : 0)}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 502, Message => "[4] Expression result invalid: " & To_String (Value)); -- Choice expressions E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 3 * 3}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 9, Message => "[5] Expression result invalid: " & To_String (Value)); -- Choice expressions using strings E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 'A string'}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_String (Value) = "A string", Message => "[6] Expression result invalid: " & To_String (Value)); end Test_Expression; package Caller is new Util.Test_Caller (Test); Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Caller.Add_Test (Ret, "Test To_Object (Integer)", Test_To_Object_Integer'Access); Caller.Add_Test (Ret, "Test Expressions", Test_Expression'Access); EL.Expressions.Tests.Add_Tests (Ret); EL.Contexts.Tests.Add_Tests (Ret); EL.Beans.Tests.Add_Tests (Ret); EL.Utils.Tests.Add_Tests (Ret); return Ret; end Suite; end EL.Testsuite;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with EL.Expressions; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Expressions.Tests; with EL.Beans.Tests; with EL.Contexts.Tests; with EL.Utils.Tests; package body EL.Testsuite is use EL.Objects; -- ------------------------------ -- Test object integer -- ------------------------------ procedure Test_To_Object_Integer (T : in out Test) is begin declare Value : constant EL.Objects.Object := To_Object (Integer (1)); begin T.Assert (Condition => To_Integer (Value) = 1, Message => "Object.To_Integer: invalid integer returned"); T.Assert (Condition => To_Long_Integer (Value) = 1, Message => "Object.To_Long_Integer: invalid integer returned"); T.Assert (Condition => To_Boolean (Value), Message => "Object.To_Boolean: invalid return"); declare V2 : constant EL.Objects.Object := Value + To_Object (Long_Integer (100)); begin T.Assert (Condition => To_Integer (V2) = 101, Message => "To_Integer invalid after an add"); end; end; end Test_To_Object_Integer; -- ------------------------------ -- Test object integer -- ------------------------------ procedure Test_Expression (T : in out Test) is E : EL.Expressions.Expression; Value : Object; Ctx : EL.Contexts.Default.Default_Context; begin -- Positive number E := EL.Expressions.Create_Expression ("12345678901", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Long_Long_Integer (Value) = Long_Long_Integer (12345678901), Message => "[1] Expression result invalid: " & To_String (Value)); -- Negative number E := EL.Expressions.Create_Expression ("-10", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = -10, Message => "[2] Expression result invalid: " & To_String (Value)); -- Simple add E := EL.Expressions.Create_Expression ("#{1+1}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 2, Message => "[2.1] Expression result invalid: " & To_String (Value)); -- Constant expressions E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 492, Message => "[3] Expression result invalid: " & To_String (Value)); -- Constant expressions E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4 + (23? 10 : 0)}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 502, Message => "[4] Expression result invalid: " & To_String (Value)); -- Choice expressions E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 3 * 3}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_Integer (Value) = 9, Message => "[5] Expression result invalid: " & To_String (Value)); -- Choice expressions using strings E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 'A string'}", Ctx); Value := E.Get_Value (Ctx); T.Assert (Condition => To_String (Value) = "A string", Message => "[6] Expression result invalid: " & To_String (Value)); end Test_Expression; package Caller is new Util.Test_Caller (Test, "EL"); Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Caller.Add_Test (Ret, "Test To_Object (Integer)", Test_To_Object_Integer'Access); Caller.Add_Test (Ret, "Test Expressions", Test_Expression'Access); EL.Expressions.Tests.Add_Tests (Ret); EL.Contexts.Tests.Add_Tests (Ret); EL.Beans.Tests.Add_Tests (Ret); EL.Utils.Tests.Add_Tests (Ret); return Ret; end Suite; end EL.Testsuite;
Use the test name EL
Use the test name EL
Ada
apache-2.0
stcarrez/ada-el
32d1ea8fc027a1a4f7cc3bada95a17652debcbf3
regtests/util-commands-tests.adb
regtests/util-commands-tests.adb
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- 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 GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration); -- Write the help associated with the command. procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); D.Usage (Args); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- 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 GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type); -- Write the help associated with the command. procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); declare Ctx : Test_Context_Type; begin D.Usage (Args, Ctx); C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3683b400aa9280261e66ca5b8c67a33a37360a4d
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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 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; -- 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; -- 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;
Declare the Set_Server procedure
Declare the Set_Server procedure
Ada
apache-2.0
stcarrez/ada-ado
1daad8b1196743e8900ad6c9d97b1caea76a7963
tools/druss-commands-status.adb
tools/druss-commands-status.adb
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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 Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.0.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.length", "x")); Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", "")); Print_Uptime (Console, F_UPTIME, Gateway.Device.Get ("device.uptime", "")); Console.End_Row; N := N + 1; Gateway.Hosts.Save_Properties ("sum-" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 16); Console.Print_Title (F_WAN_IP, "WAN IP", 16); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.Print_Title (F_UPTIME, "Uptime", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Status; -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Do_Status (Args, Context); 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 ("status: Control and get status about the Bbox Wifi"); Put_Line ("Usage: wifi {<action>} [<parameters>]"); New_Line; Put_Line (" status [IP]... Turn ON the wifi on the Bbox."); Put_Line (" wifi off [IP]... Turn OFF the wifi on the Bbox."); Put_Line (" wifi show Show information about the wifi on the Bbox."); Put_Line (" wifi devices Show the wifi devices which are connected."); end Help; end Druss.Commands.Status;
----------------------------------------------------------------------- -- druss-commands-status -- Druss status commands -- 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.Properties; with Util.Strings; with Druss.Gateways; package body Druss.Commands.Status is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Status (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; N : Natural := 0; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Refresh; Console.Start_Row; Console.Print_Field (F_IP_ADDR, Gateway.Ip); Console.Print_Field (F_WAN_IP, Gateway.Wan.Get ("wan.ip.address", " ")); Print_Status (Console, F_INTERNET, Gateway.Wan.Get ("wan.internet.state", " ")); Console.Print_Field (F_VOIP, Gateway.Voip.Get ("voip.0.status", " ")); Print_On_Off (Console, F_WIFI, Gateway.Wifi.Get ("wireless.radio.24.enable", " ")); if not Gateway.Wifi.Exists ("wireless.radio.5.enable") then Console.Print_Field (F_WIFI5, ""); else Print_On_Off (Console, F_WIFI5, Gateway.Wifi.Get ("wireless.radio.5.enable", " ")); end if; Console.Print_Field (F_ACCESS_CONTROL, Gateway.IPtv.Get ("iptv.length", "x")); Console.Print_Field (F_DEVICES, Gateway.Hosts.Get ("hosts.list.length", "")); Print_Uptime (Console, F_UPTIME, Gateway.Device.Get ("device.uptime", "")); Console.End_Row; N := N + 1; Gateway.Hosts.Save_Properties ("sum-" & Util.Strings.Image (N) & ".properties"); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_IP_ADDR, "LAN IP", 16); Console.Print_Title (F_WAN_IP, "WAN IP", 16); Console.Print_Title (F_INTERNET, "Internet", 9); Console.Print_Title (F_VOIP, "VoIP", 6); Console.Print_Title (F_WIFI, "Wifi 2.4G", 10); Console.Print_Title (F_WIFI5, "Wifi 5G", 10); Console.Print_Title (F_ACCESS_CONTROL, "Parental", 10); Console.Print_Title (F_DYNDNS, "DynDNS", 10); Console.Print_Title (F_DEVICES, "Devices", 12); Console.Print_Title (F_UPTIME, "Uptime", 12); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Status; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Status (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "status: give information about the Bbox status"); Console.Notice (N_HELP, "Usage: wifi {<action>} [<parameters>]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " status [IP]... Give information about the Bbox status"); end Help; end Druss.Commands.Status;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/bbox-ada-api
d1e413a42750d1e85c1aae986cd2fcc015ac089f
ARM/STM32/drivers/stm32-pwm.ads
ARM/STM32/drivers/stm32-pwm.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides a convenient pulse width modulation (PWM) generation -- abstract data type. -- Example use, with arbitrary hardware selections: -- Output : PWM_Modulator; -- -- Initialise_PWM_Modulator -- (Output, -- Requested_Frequency => 30_000.0, -- PWM_Timer => Timer_4'Access, -- PWM_AF => GPIO_AF_TIM4, -- Enable_PWM_Timer_Clock => RCC.TIM4_Clock_Enable'Access); -- -- Attach_PWM_Channel -- (Output, -- Channel_2, -- (GPIO_D'Access, Pin_13), -- must match selected channel -- RCC.GPIOD_Clock_Enable'Access); -- -- Enable_PWM_Channel (Output, Channel_2); -- -- Set_Duty_Cycle (Output, Channel_2, Value); with STM32.GPIO; use STM32.GPIO; with STM32.Timers; use STM32.Timers; package STM32.PWM is pragma Elaborate_Body; type PWM_Modulator is limited private; procedure Initialise_PWM_Modulator (This : in out PWM_Modulator; Requested_Frequency : Float; PWM_Timer : not null access Timer; PWM_AF : GPIO_Alternate_Function) with Post => (for all Channel in Timer_Channel => (not Attached (This, Channel))); -- Initializes the specified timer for PWM generation at the requested -- frequency. You must attach at least one channel to the modulator in -- order to drive PWM output values. procedure Attach_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel; Point : GPIO_Point) with Post => Attached (This, Channel) and not Enabled (This, Channel) and Current_Duty_Cycle (This, Channel) = 0; -- Initializes the channel on the timer associated with This, and the -- corresponding GPIO port/pin pair, for PWM output. May be called multiple -- times for the same PWM_Modulator object, with different channels, -- because the corresponding timer can drive multiple channels (assuming -- such a timer is in use). procedure Enable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) with Post => Enabled (This, Channel); function Enabled (This : PWM_Modulator; Channel : Timer_Channel) return Boolean; procedure Disable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) with Post => not Enabled (This, Channel); subtype Percentage is Integer range 0 .. 100; procedure Set_Duty_Cycle (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Percentage) with Inline, Pre => (Attached (This, Channel) or else raise Not_Attached) and Enabled (This, Channel), Post => Current_Duty_Cycle (This, Channel) = Value; -- Sets the pulse width such that the requested percentage is achieved. function Current_Duty_Cycle (This : PWM_Modulator; Channel : Timer_Channel) return Percentage with Inline, Pre => Attached (This, Channel) or else raise Not_Attached; subtype Microseconds is Word; procedure Set_Duty_Time (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Microseconds) with Inline, Pre => (Attached (This, Channel) or else raise Not_Attached) and Enabled (This, Channel); -- Set the pulse width such that the requested number of microseconds is -- achieved. Raises Invalid_Request if the requested time is greater than -- the period previously configured via Initialise_PWM_Modulator. Invalid_Request : exception; -- Raised when the requested frequency is too high or too low for the given -- timer and system clocks when calling Initialize_PWM_Modulator, or when -- the requested time is too high for the specified frequency when calling -- Set_Duty_Time Unknown_Timer : exception; -- Raised if a timer that is not physically present is passed to -- Initialize_PWM_Modulator Not_Attached : exception; function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean; private type PWM_Output is record Duty_Cycle : Percentage := 0; Attached : Boolean := False; end record; type PWM_Outputs is array (Timer_Channel) of PWM_Output; type PWM_Modulator is record Output_Timer : access Timer; Outputs : PWM_Outputs; Timer_Period : Word; Frequency : Word; AF : GPIO_Alternate_Function; end record; end STM32.PWM;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides a convenient pulse width modulation (PWM) generation -- abstract data type. -- Example use, with arbitrary hardware selections: -- Output : PWM_Modulator; -- -- Initialise_PWM_Modulator -- (Output, -- Requested_Frequency => 30_000.0, -- PWM_Timer => Timer_4'Access, -- PWM_AF => GPIO_AF_TIM4, -- Enable_PWM_Timer_Clock => RCC.TIM4_Clock_Enable'Access); -- -- Attach_PWM_Channel -- (Output, -- Channel_2, -- (GPIO_D'Access, Pin_13), -- must match selected channel -- RCC.GPIOD_Clock_Enable'Access); -- -- Enable_PWM_Channel (Output, Channel_2); -- -- Set_Duty_Cycle (Output, Channel_2, Value); with STM32.GPIO; use STM32.GPIO; with STM32.Timers; use STM32.Timers; package STM32.PWM is pragma Elaborate_Body; type PWM_Modulator is limited private; procedure Initialise_PWM_Modulator (This : in out PWM_Modulator; Requested_Frequency : Float; PWM_Timer : not null access Timer; PWM_AF : GPIO_Alternate_Function) with Post => (for all Channel in Timer_Channel => (not Attached (This, Channel))); -- Initializes the specified timer for PWM generation at the requested -- frequency. You must attach at least one channel to the modulator in -- order to drive PWM output values. procedure Attach_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel; Point : GPIO_Point) with Post => Attached (This, Channel) and not Enabled (This, Channel) and Current_Duty_Cycle (This, Channel) = 0; -- Initializes the channel on the timer associated with This, and the -- corresponding GPIO port/pin pair, for PWM output. May be called multiple -- times for the same PWM_Modulator object, with different channels, -- because the corresponding timer can drive multiple channels (assuming -- such a timer is in use). procedure Enable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) with Post => Enabled (This, Channel); function Enabled (This : PWM_Modulator; Channel : Timer_Channel) return Boolean; procedure Disable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) with Post => not Enabled (This, Channel); subtype Percentage is Integer range 0 .. 100; procedure Set_Duty_Cycle (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Percentage) with Inline, Pre => (Attached (This, Channel) or else raise Not_Attached), Post => Current_Duty_Cycle (This, Channel) = Value; -- Sets the pulse width such that the requested percentage is achieved. function Current_Duty_Cycle (This : PWM_Modulator; Channel : Timer_Channel) return Percentage with Inline, Pre => Attached (This, Channel) or else raise Not_Attached; subtype Microseconds is Word; procedure Set_Duty_Time (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Microseconds) with Inline, Pre => (Attached (This, Channel) or else raise Not_Attached); -- Set the pulse width such that the requested number of microseconds is -- achieved. Raises Invalid_Request if the requested time is greater than -- the period previously configured via Initialise_PWM_Modulator. Invalid_Request : exception; -- Raised when the requested frequency is too high or too low for the given -- timer and system clocks when calling Initialize_PWM_Modulator, or when -- the requested time is too high for the specified frequency when calling -- Set_Duty_Time Unknown_Timer : exception; -- Raised if a timer that is not physically present is passed to -- Initialize_PWM_Modulator Not_Attached : exception; function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean; private type PWM_Output is record Duty_Cycle : Percentage := 0; Attached : Boolean := False; end record; type PWM_Outputs is array (Timer_Channel) of PWM_Output; type PWM_Modulator is record Output_Timer : access Timer; Outputs : PWM_Outputs; Timer_Period : Word; Frequency : Word; AF : GPIO_Alternate_Function; end record; end STM32.PWM;
Remove Enabled as precondition for PWM set duty procedures
Remove Enabled as precondition for PWM set duty procedures The channel doesn't need to be enabled before setting duty value and it can be useful to set a value before enabling it.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
d1b76e256c1ea5b970aa0008ff5c8ffcd8f83345
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Update the Create_Statement operation to use the normal query definition
Update the Create_Statement operation to use the normal query definition
Ada
apache-2.0
Letractively/ada-ado
8d422d64f57b8461c4c22a1c6e1f76fd42ee3b96
awa/regtests/awa-users-tests.ads
awa/regtests/awa-users-tests.ads
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Users.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Test creation of user by simulating web requests. procedure Test_Create_User (T : in out Test); procedure Test_Logout_User (T : in out Test); -- Test user authentication by simulating a web request. procedure Test_Login_User (T : in out Test); -- Test the reset password by simulating web requests. procedure Test_Reset_Password_User (T : in out Test); -- Run the recovery password process for the given user and change the password. procedure Recover_Password (T : in out Test; Email : in String; Password : in String); end AWA.Users.Tests;
----------------------------------------------------------------------- -- awa-users-tests -- Unit tests for AWA users -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Users.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Test creation of user by simulating web requests. procedure Test_Create_User (T : in out Test); procedure Test_Logout_User (T : in out Test); -- Test user authentication by simulating a web request. procedure Test_Login_User (T : in out Test); -- Test the reset password by simulating web requests. procedure Test_Reset_Password_User (T : in out Test); -- Test OAuth access using a fake OAuth provider. procedure Test_OAuth_Login (T : in out Test); -- Run the recovery password process for the given user and change the password. procedure Recover_Password (T : in out Test; Email : in String; Password : in String); end AWA.Users.Tests;
Declare the Test_OAuth_Login procedure
Declare the Test_OAuth_Login procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bb9ca8b957bfa51590aacc05ea3a3409622dac22
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare the To_String function
Declare the To_String function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
83bbb35c1cb7bc57a291e9e4068408306708f9ab
awa/src/awa-events-services.adb
awa/src/awa-events-services.adb
----------------------------------------------------------------------- -- awa-events-services -- AWA Event Manager -- Copyright (C) 2012, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ADO.SQL; with ADO.Sessions; with AWA.Events.Dispatchers.Tasks; with AWA.Events.Dispatchers.Actions; package body AWA.Events.Services is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services"); -- ------------------------------ -- Send the event to the modules that subscribed to it. -- The event is sent on each event queue. Event queues will dispatch the event -- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous -- or asynchronous reception of the event depends on the event queue. -- ------------------------------ procedure Send (Manager : in Event_Manager; Event : in Module_Event'Class) is procedure Send_Queue (Queue : in Queue_Dispatcher); procedure Send_Queue (Queue : in Queue_Dispatcher) is begin if Queue.Queue.Is_Null then Queue.Dispatcher.Dispatch (Event); else Queue.Queue.Enqueue (Event); end if; end Send_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; -- Find the event queues associated with the event. Post the event on each queue. -- Some queue can dispatch the event immediately while some others may dispatched it -- asynchronously. declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Sending event {0} but there is no listener", Name.all); else Log.Debug ("Sending event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access); Queue_Dispatcher_Lists.Next (Pos); exit when not Queue_Dispatcher_Lists.Has_Element (Pos); end loop; end if; end; end Send; -- ------------------------------ -- Set the event message type which correspond to the <tt>Kind</tt> event index. -- ------------------------------ procedure Set_Message_Type (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Kind : in Event_Index) is begin if not Event_Arrays.Is_Valid (Kind) then Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind)); raise Not_Found; end if; Event.Set_Status (AWA.Events.Models.QUEUED); Event.Set_Message_Type (Manager.Actions (Kind).Event); end Set_Message_Type; -- ------------------------------ -- Set the event queue associated with the event message. The event queue identified by -- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance. -- ------------------------------ procedure Set_Event_Queue (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Name : in String) is Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name); begin Event.Set_Queue (Queue.Get_Queue); end Set_Event_Queue; -- ------------------------------ -- Dispatch the event identified by <b>Event</b> and associated with the event -- queue <b>Queue</b>. The event actions which are associated with the event are -- executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref; Event : in Module_Event'Class) is procedure Find_Queue (List : in Queue_Dispatcher); Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin if List.Queue = Queue then List.Dispatcher.Dispatch (Event); Found := True; end if; end Find_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatching event {0} but there is no listener", Name.all); else Log.Debug ("Dispatching event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatched event {0} but there was no listener", Name.all); exit; end if; end loop; end if; end; end Dispatch; -- ------------------------------ -- Find the event queue identified by the given name. -- ------------------------------ function Find_Queue (Manager : in Event_Manager; Name : in String) return AWA.Events.Queues.Queue_Ref is Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name); begin if Queues.Maps.Has_Element (Pos) then return Queues.Maps.Element (Pos); else Log.Error ("Event queue {0} not found", Name); return AWA.Events.Queues.Null_Queue; end if; end Find_Queue; -- ------------------------------ -- Add the event queue in the registry. -- ------------------------------ procedure Add_Queue (Manager : in out Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref) is Name : constant String := Queue.Get_Name; begin if Manager.Queues.Contains (Name) then Log.Error ("Event queue {0} already defined"); else Log.Info ("Adding event queue {0}", Name); end if; Manager.Queues.Include (Key => Name, New_Item => Queue); end Add_Queue; -- ------------------------------ -- Add an action invoked when the event identified by <b>Event</b> is sent. -- The event is posted on the queue identified by <b>Queue</b>. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Event_Manager; Event : in String; Queue : in AWA.Events.Queues.Queue_Ref; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is procedure Find_Queue (List : in Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin if List.Dispatcher = null then List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher (Application => Manager.Application.all'Access); end if; List.Dispatcher.Add_Action (Action, Params); end Add_Action; Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin Found := List.Queue = Queue; end Find_Queue; Index : constant Event_Index := Find_Event_Index (Event); Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First; begin Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event); -- Find the queue. while Queue_Dispatcher_Lists.Has_Element (Pos) loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); end loop; -- Create it if it does not exist. if not Found then declare New_Queue : Queue_Dispatcher; begin New_Queue.Queue := Queue; Manager.Actions (Index).Queues.Append (New_Queue); Pos := Manager.Actions (Index).Queues.Last; end; end if; -- And append the new action to the event queue. Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access); end Add_Action; -- ------------------------------ -- Add a dispatcher to process the event queues matching the <b>Match</b> string. -- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>. -- ------------------------------ procedure Add_Dispatcher (Manager : in out Event_Manager; Match : in String; Count : in Positive; Priority : in Positive) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'", Positive'Image (Count), Positive'Image (Priority), Match); for I in Manager.Dispatchers'Range loop if Manager.Dispatchers (I) = null then Manager.Dispatchers (I) := AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access, Match, Count, Priority); return; end if; end loop; Log.Error ("Implementation limit is reached. Too many dispatcher."); end Add_Dispatcher; -- ------------------------------ -- Initialize the event manager. -- ------------------------------ procedure Initialize (Manager : in out Event_Manager; App : in Application_Access) is procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref); Msg_Types : AWA.Events.Models.Message_Type_Vector; Query : ADO.SQL.Query; procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is Name : constant String := Msg.Get_Name; begin declare Index : constant Event_Index := Find_Event_Index (Name); begin Manager.Actions (Index).Event := Msg; end; exception when others => Log.Warn ("Event {0} is no longer used", Name); end Set_Events; DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last)); Manager.Application := App; DB.Begin_Transaction; Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last); AWA.Events.Models.List (Object => Msg_Types, Session => DB, Query => Query); declare Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First; begin while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access); AWA.Events.Models.Message_Type_Vectors.Next (Pos); end loop; end; for I in Manager.Actions'Range loop if Manager.Actions (I).Event.Is_Null then declare Name : constant Name_Access := Get_Event_Type_Name (I); begin Log.Info ("Creating event type {0} in database", Name.all); Manager.Actions (I).Event.Set_Name (Name.all); Manager.Actions (I).Event.Save (DB); end; end if; end loop; DB.Commit; end Initialize; -- ------------------------------ -- Start the event manager. The dispatchers are configured to dispatch the event queues -- and tasks are started to process asynchronous events. -- ------------------------------ procedure Start (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref); -- ------------------------------ -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. -- ------------------------------ procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref) is pragma Unreferenced (Key); Added : Boolean := False; begin for I in reverse Manager.Dispatchers'Range loop if Manager.Dispatchers (I) /= null then Manager.Dispatchers (I).Add_Queue (Queue, Added); exit when Added; end if; end loop; end Associate_Dispatcher; Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First; begin Log.Info ("Starting the event manager"); while AWA.Events.Queues.Maps.Has_Element (Iter) loop Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access); AWA.Events.Queues.Maps.Next (Iter); end loop; -- Start the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Start; end loop; end Start; -- ------------------------------ -- Stop the event manager. -- ------------------------------ procedure Stop (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Stopping the event manager"); -- Stop the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Stop; end loop; end Stop; -- ------------------------------ -- Get the application associated with the event manager. -- ------------------------------ function Get_Application (Manager : in Event_Manager) return Application_Access is begin return Manager.Application; end Get_Application; -- ------------------------------ -- Finalize the queue dispatcher releasing the dispatcher memory. -- ------------------------------ procedure Finalize (Object : in out Queue_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin Free (Object.Dispatcher); end Finalize; -- ------------------------------ -- Finalize the event queues and the dispatchers. -- ------------------------------ procedure Finalize (Object : in out Event_Queues) is begin loop declare Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First; begin exit when not Queue_Dispatcher_Lists.Has_Element (Pos); Object.Queues.Update_Element (Position => Pos, Process => Finalize'Access); Object.Queues.Delete_First; end; end loop; end Finalize; -- ------------------------------ -- Finalize the event manager by releasing the allocated storage. -- ------------------------------ overriding procedure Finalize (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Event_Queues_Array, Name => Event_Queues_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin -- Stop the dispatcher first. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Free (Manager.Dispatchers (I)); end loop; if Manager.Actions /= null then for I in Manager.Actions'Range loop Finalize (Manager.Actions (I)); end loop; Free (Manager.Actions); end if; end Finalize; end AWA.Events.Services;
----------------------------------------------------------------------- -- awa-events-services -- AWA Event Manager -- Copyright (C) 2012, 2015, 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.Log.Loggers; with ADO.SQL; with ADO.Sessions; with AWA.Events.Dispatchers.Tasks; with AWA.Events.Dispatchers.Actions; package body AWA.Events.Services is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Events.Services"); -- ------------------------------ -- Send the event to the modules that subscribed to it. -- The event is sent on each event queue. Event queues will dispatch the event -- by invoking immediately or later on the <b>Dispatch</b> operation. The synchronous -- or asynchronous reception of the event depends on the event queue. -- ------------------------------ procedure Send (Manager : in Event_Manager; Event : in Module_Event'Class) is procedure Send_Queue (Queue : in Queue_Dispatcher); procedure Send_Queue (Queue : in Queue_Dispatcher) is begin if not Queue.Queue.Has_Queue then Queue.Dispatcher.Dispatch (Event); else Queue.Queue.Enqueue (Event); end if; end Send_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot send event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; -- Find the event queues associated with the event. Post the event on each queue. -- Some queue can dispatch the event immediately while some others may dispatched it -- asynchronously. declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Sending event {0} but there is no listener", Name.all); else Log.Debug ("Sending event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Send_Queue'Access); Queue_Dispatcher_Lists.Next (Pos); exit when not Queue_Dispatcher_Lists.Has_Element (Pos); end loop; end if; end; end Send; -- ------------------------------ -- Set the event message type which correspond to the <tt>Kind</tt> event index. -- ------------------------------ procedure Set_Message_Type (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Kind : in Event_Index) is begin if not Event_Arrays.Is_Valid (Kind) then Log.Error ("Cannot send event type {0}", Event_Index'Image (Kind)); raise Not_Found; end if; Event.Set_Status (AWA.Events.Models.QUEUED); Event.Set_Message_Type (Manager.Actions (Kind).Event); end Set_Message_Type; -- ------------------------------ -- Set the event queue associated with the event message. The event queue identified by -- <tt>Name</tt> is searched to find the <tt>Queue_Ref</tt> instance. -- ------------------------------ procedure Set_Event_Queue (Manager : in Event_Manager; Event : in out AWA.Events.Models.Message_Ref; Name : in String) is Queue : constant AWA.Events.Queues.Queue_Ref := Manager.Find_Queue (Name); begin Event.Set_Queue (Queue.Get_Queue); end Set_Event_Queue; -- ------------------------------ -- Dispatch the event identified by <b>Event</b> and associated with the event -- queue <b>Queue</b>. The event actions which are associated with the event are -- executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref; Event : in Module_Event'Class) is procedure Find_Queue (List : in Queue_Dispatcher); Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin if List.Queue = Queue then List.Dispatcher.Dispatch (Event); Found := True; end if; end Find_Queue; Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); begin if Name = null then Log.Error ("Cannot dispatch event type {0}", Event_Index'Image (Event.Kind)); raise Not_Found; end if; declare Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; begin if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatching event {0} but there is no listener", Name.all); else Log.Debug ("Dispatching event {0}", Name.all); loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); if not Queue_Dispatcher_Lists.Has_Element (Pos) then Log.Debug ("Dispatched event {0} but there was no listener", Name.all); exit; end if; end loop; end if; end; end Dispatch; -- ------------------------------ -- Find the event queue identified by the given name. -- ------------------------------ function Find_Queue (Manager : in Event_Manager; Name : in String) return AWA.Events.Queues.Queue_Ref is Pos : constant Queues.Maps.Cursor := Manager.Queues.Find (Name); begin if Queues.Maps.Has_Element (Pos) then return Queues.Maps.Element (Pos); else Log.Error ("Event queue {0} not found", Name); return AWA.Events.Queues.Null_Queue; end if; end Find_Queue; -- ------------------------------ -- Add the event queue in the registry. -- ------------------------------ procedure Add_Queue (Manager : in out Event_Manager; Queue : in AWA.Events.Queues.Queue_Ref) is Name : constant String := Queue.Get_Name; begin if Manager.Queues.Contains (Name) then Log.Error ("Event queue {0} already defined"); else Log.Info ("Adding event queue {0}", Name); end if; Manager.Queues.Include (Key => Name, New_Item => Queue); end Add_Queue; -- ------------------------------ -- Add an action invoked when the event identified by <b>Event</b> is sent. -- The event is posted on the queue identified by <b>Queue</b>. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Event_Manager; Event : in String; Queue : in AWA.Events.Queues.Queue_Ref; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is procedure Find_Queue (List : in Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher); procedure Add_Action (List : in out Queue_Dispatcher) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin if List.Dispatcher = null then List.Dispatcher := AWA.Events.Dispatchers.Actions.Create_Dispatcher (Application => Manager.Application.all'Access); end if; List.Dispatcher.Add_Action (Action, Params); end Add_Action; Found : Boolean := False; procedure Find_Queue (List : in Queue_Dispatcher) is begin Found := List.Queue = Queue; end Find_Queue; Index : constant Event_Index := Find_Event_Index (Event); Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Index).Queues.First; begin Log.Info ("Adding action {0} to event {1}", Action.Get_Expression, Event); -- Find the queue. while Queue_Dispatcher_Lists.Has_Element (Pos) loop Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); exit when Found; Queue_Dispatcher_Lists.Next (Pos); end loop; -- Create it if it does not exist. if not Found then declare New_Queue : Queue_Dispatcher; begin New_Queue.Queue := Queue; Manager.Actions (Index).Queues.Append (New_Queue); Pos := Manager.Actions (Index).Queues.Last; end; end if; -- And append the new action to the event queue. Manager.Actions (Index).Queues.Update_Element (Pos, Add_Action'Access); end Add_Action; -- ------------------------------ -- Add a dispatcher to process the event queues matching the <b>Match</b> string. -- The dispatcher can create up to <b>Count</b> tasks running at the priority <b>Priority</b>. -- ------------------------------ procedure Add_Dispatcher (Manager : in out Event_Manager; Match : in String; Count : in Positive; Priority : in Positive) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'", Positive'Image (Count), Positive'Image (Priority), Match); for I in Manager.Dispatchers'Range loop if Manager.Dispatchers (I) = null then Manager.Dispatchers (I) := AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access, Match, Count, Priority); return; end if; end loop; Log.Error ("Implementation limit is reached. Too many dispatcher."); end Add_Dispatcher; -- ------------------------------ -- Initialize the event manager. -- ------------------------------ procedure Initialize (Manager : in out Event_Manager; App : in Application_Access) is procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref); Msg_Types : AWA.Events.Models.Message_Type_Vector; Query : ADO.SQL.Query; procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is Name : constant String := Msg.Get_Name; begin declare Index : constant Event_Index := Find_Event_Index (Name); begin Manager.Actions (Index).Event := Msg; end; exception when others => Log.Warn ("Event {0} is no longer used", Name); end Set_Events; DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Log.Info ("Initializing {0} events", Event_Index'Image (Event_Arrays.Get_Last)); Manager.Application := App; DB.Begin_Transaction; Manager.Actions := new Event_Queues_Array (1 .. Event_Arrays.Get_Last); AWA.Events.Models.List (Object => Msg_Types, Session => DB, Query => Query); declare Pos : AWA.Events.Models.Message_Type_Vectors.Cursor := Msg_Types.First; begin while AWA.Events.Models.Message_Type_Vectors.Has_Element (Pos) loop AWA.Events.Models.Message_Type_Vectors.Query_Element (Pos, Set_Events'Access); AWA.Events.Models.Message_Type_Vectors.Next (Pos); end loop; end; for I in Manager.Actions'Range loop if Manager.Actions (I).Event.Is_Null then declare Name : constant Name_Access := Get_Event_Type_Name (I); begin Log.Info ("Creating event type {0} in database", Name.all); Manager.Actions (I).Event.Set_Name (Name.all); Manager.Actions (I).Event.Save (DB); end; end if; end loop; DB.Commit; end Initialize; -- ------------------------------ -- Start the event manager. The dispatchers are configured to dispatch the event queues -- and tasks are started to process asynchronous events. -- ------------------------------ procedure Start (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref); -- ------------------------------ -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. -- ------------------------------ procedure Associate_Dispatcher (Key : in String; Queue : in out AWA.Events.Queues.Queue_Ref) is pragma Unreferenced (Key); Added : Boolean := False; begin for I in reverse Manager.Dispatchers'Range loop if Manager.Dispatchers (I) /= null then Manager.Dispatchers (I).Add_Queue (Queue, Added); exit when Added; end if; end loop; end Associate_Dispatcher; Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First; begin Log.Info ("Starting the event manager"); while AWA.Events.Queues.Maps.Has_Element (Iter) loop Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access); AWA.Events.Queues.Maps.Next (Iter); end loop; -- Start the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Start; end loop; end Start; -- ------------------------------ -- Stop the event manager. -- ------------------------------ procedure Stop (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; begin Log.Info ("Stopping the event manager"); -- Stop the dispatchers. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Manager.Dispatchers (I).Stop; end loop; end Stop; -- ------------------------------ -- Get the application associated with the event manager. -- ------------------------------ function Get_Application (Manager : in Event_Manager) return Application_Access is begin return Manager.Application; end Get_Application; -- ------------------------------ -- Finalize the queue dispatcher releasing the dispatcher memory. -- ------------------------------ procedure Finalize (Object : in out Queue_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin Free (Object.Dispatcher); end Finalize; -- ------------------------------ -- Finalize the event queues and the dispatchers. -- ------------------------------ procedure Finalize (Object : in out Event_Queues) is begin loop declare Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First; begin exit when not Queue_Dispatcher_Lists.Has_Element (Pos); Object.Queues.Update_Element (Position => Pos, Process => Finalize'Access); Object.Queues.Delete_First; end; end loop; end Finalize; -- ------------------------------ -- Finalize the event manager by releasing the allocated storage. -- ------------------------------ overriding procedure Finalize (Manager : in out Event_Manager) is use type AWA.Events.Dispatchers.Dispatcher_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Event_Queues_Array, Name => Event_Queues_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, Name => AWA.Events.Dispatchers.Dispatcher_Access); begin -- Stop the dispatcher first. for I in Manager.Dispatchers'Range loop exit when Manager.Dispatchers (I) = null; Free (Manager.Dispatchers (I)); end loop; if Manager.Actions /= null then for I in Manager.Actions'Range loop Finalize (Manager.Actions (I)); end loop; Free (Manager.Actions); end if; end Finalize; end AWA.Events.Services;
Use the Has_Queue operation in Senq_Queue procedure
Use the Has_Queue operation in Senq_Queue procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
89bd9fd0717b7170c44ac1842be3312b0a2138d0
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out 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; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; 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 Security_Context_Access; 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; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- 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); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out 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; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); 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;
Rename the package URLs
Rename the package URLs
Ada
apache-2.0
Letractively/ada-security
b7478c50fe8f81b3a00b7e0eba131ef523f17ca2
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Iterate_Files (Path : in String; Dir : in out Directory; Depth : in Natural; Update : access procedure (P : in String; F : in out File)) is use Ada.Strings.Unbounded; Iter : File_Vectors.Cursor := Dir.Files.First; procedure Iterate_File (Item : in out File) is begin Update (Path, Item); end Iterate_File; procedure Iterate_Child (Item : in out Directory) is begin Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update); end Iterate_Child; begin while File_Vectors.Has_Element (Iter) loop Dir.Files.Update_Element (Iter, Iterate_File'Access); File_Vectors.Next (Iter); end loop; if Depth > 0 and then Dir.Children /= null then declare Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First; begin while Directory_Vectors.Has_Element (Dir_Iter) loop Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access); Directory_Vectors.Next (Dir_Iter); end loop; end; end if; end Iterate_Files; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
Remove the old Iterate_Files procedure
Remove the old Iterate_Files procedure
Ada
apache-2.0
stcarrez/babel
54b662e24976fdda1ef44c28a904bbb4be209b6c
src/util-streams.adb
src/util-streams.adb
----------------------------------------------------------------------- -- Util.Streams -- Stream utilities -- Copyright (C) 2010, 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. ----------------------------------------------------------------------- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT 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;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a9c1ae78a8c9c7be5972e8da3af6612412580bcc
src/wiki-filters.ads
src/wiki-filters.ads
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The `Wiki.Filters` package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The `Filter_Type` -- implements the operations that the `Wiki.Parsers` will use to populate the document. -- A filter can do some operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the `Filter_Type` type must be used as a base type -- and some of the operations have to be overridden. The default `Filter_Type` operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- -- @include wiki-filters-toc.ads -- @include wiki-filters-html.ads -- @include wiki-filters-collectors.ads -- @include wiki-filters-autolink.ads -- @include wiki-filters-variables.ads package Wiki.Filters is pragma Preelaborate; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is limited new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural); -- Add a list (<ul> or <ol>) starting at the given number. procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Add a new row to the current table. procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List); -- Finish the creation of the table. procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); -- Finish the document after complete wiki text has been parsed. procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); type Filter_Chain is new Filter_Type with private; -- Add the filter at beginning of the filter chain. procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access); -- Internal operation to copy the filter chain. procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class); private type Filter_Type is limited new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; type Filter_Chain is new Filter_Type with null record; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The `Wiki.Filters` package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The `Filter_Type` -- implements the operations that the `Wiki.Parsers` will use to populate the document. -- A filter can do some operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the `Filter_Type` type must be used as a base type -- and some of the operations have to be overridden. The default `Filter_Type` operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- -- @include wiki-filters-toc.ads -- @include wiki-filters-html.ads -- @include wiki-filters-collectors.ads -- @include wiki-filters-autolink.ads -- @include wiki-filters-variables.ads package Wiki.Filters is pragma Preelaborate; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is limited new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a definition item at end of the document. procedure Add_Definition (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Definition : in Wiki.Strings.WString); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural); -- Add a list (<ul> or <ol>) starting at the given number. procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Add a new row to the current table. procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List); -- Finish the creation of the table. procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); -- Finish the document after complete wiki text has been parsed. procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document); type Filter_Chain is new Filter_Type with private; -- Add the filter at beginning of the filter chain. procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access); -- Internal operation to copy the filter chain. procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class); private type Filter_Type is limited new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; type Filter_Chain is new Filter_Type with null record; end Wiki.Filters;
Declare the Add_Definition procedure
Declare the Add_Definition procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b582e01a7532e6b97b67ba7c55a9b35a2d5ac664
mat/src/mat-types.adb
mat/src/mat-types.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- 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 Interfaces; package body MAT.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String is use type Interfaces.Unsigned_64; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint64 := Value; N : Uint64; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Format the target time to a printable representation. -- ------------------------------ function Tick_Image (Value : in Target_Tick_Ref) return String is use Interfaces; Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32)); Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#); Frac : constant String := Interfaces.Unsigned_32'Image (Usec); Img : String (1 .. 6) := (others => '0'); begin Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last); return Interfaces.Unsigned_32'Image (Sec) & "." & Img; end Tick_Image; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is use Interfaces; Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right)); Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#); Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#); begin if Usec1 < Usec2 then Res := Res and 16#ffffffff00000000#; Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#); Res := Res or Target_Tick_Ref (1000000 - (Usec2 - Usec1)); end if; return Res; end "-"; end MAT.Types;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String is use type Interfaces.Unsigned_64; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint64 := Value; N : Uint64; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Format the target time to a printable representation. -- ------------------------------ function Tick_Image (Value : in Target_Tick_Ref) return String is use Interfaces; Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32)); Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#); Frac : constant String := Interfaces.Unsigned_32'Image (Usec); Img : String (1 .. 6) := (others => '0'); begin Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last); return Interfaces.Unsigned_32'Image (Sec) & "." & Img; end Tick_Image; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is use Interfaces; Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right)); Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#); Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#); begin if Usec1 < Usec2 then Res := Res and 16#ffffffff00000000#; Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#); Res := Res or Target_Tick_Ref (1000000 - (Usec2 - Usec1)); end if; return Res; end "-"; end MAT.Types;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ab17681befd28ed9e7d0faecdd7efa7a395df286
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- 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.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Value.Get_Driver_Index); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Value.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Value.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- 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.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Update the calls to Get_SQL to use the Query_Manager instance
Update the calls to Get_SQL to use the Query_Manager instance
Ada
apache-2.0
stcarrez/ada-ado
29d755bc6c7fdd93c228737877ba853488a6d660
src/security-oauth-file_registry.adb
src/security-oauth-file_registry.adb
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.HMAC.SHA1; with Util.Log.Loggers; package body Security.OAuth.File_Registry is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.File_Registry"); -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url -- ------------------------------ procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is App : Servers.Application; begin App.Set_Application_Identifier (Props.Get (Basename & ".client_id")); App.Set_Application_Secret (Props.Get (Basename & ".client_secret")); App.Set_Application_Callback (Props.Get (Basename & ".callback_url", "")); Realm.Add_Application (App); end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading application with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid application definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} applications", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading application with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.HMAC.SHA1; with Util.Log.Loggers; package body Security.OAuth.File_Registry is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.File_Registry"); -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url -- ------------------------------ procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is App : Servers.Application; begin App.Set_Application_Identifier (Props.Get (Basename & ".client_id")); App.Set_Application_Secret (Props.Get (Basename & ".client_secret")); App.Set_Application_Callback (Props.Get (Basename & ".callback_url", "")); Realm.Add_Application (App); end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading application with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid application definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} applications", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading application with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Load from the properties the definition of users. The list of users -- is controled by the property <prefix>.list which contains a comma separated list of -- users names or ids. The user definition are represented by properties -- of the form: -- <prefix>.<user>.username -- <prefix>.<user>.password -- <prefix>.<user>.salt -- When a 'salt' property is defined, it is assumed that the password is encrypted using -- the salt and SHA1 and base64url. Otherwise, the password is in clear text. -- ------------------------------ procedure Load (Realm : in out File_Realm_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is Username : constant String := Props.Get (Basename & ".username"); Password : constant String := Props.Get (Basename & ".password"); Salt : constant String := Props.Get (Basename & ".salt", ""); begin if Salt'Length = 0 then Realm.Add_User (Username, Password); else Realm.Users.Include (Username, Salt & " " & Password); end if; end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading users with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid user definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} users", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Realm_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading users with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Log.Info ("Verify user {0} - unkown user", Username); Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Log.Info ("Verify user {0} - invalid password", Username); Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Log.Info ("Verify user {0} - grant access", Username); Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin Log.Info ("Verify token {0}", Token); Auth := null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
Implement the Load procedure to load user definitions in the Realm manager
Implement the Load procedure to load user definitions in the Realm manager
Ada
apache-2.0
stcarrez/ada-security
58c4be76c02fd2501f0f9eb299a1e947726c0bfc
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- * This instance will be associated with the current thread through a task attribute -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- * The <b>Has_Permission<b> will first look in a small cache stored in the security context. -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (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); -- 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); -- 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); -- 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); -- 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); -- 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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (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 Security.Permissions.Permission_Index) return Boolean; -- 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; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Permissions.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission<b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (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); -- 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); -- 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); -- 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); -- 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); -- 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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (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 Security.Permissions.Permission_Index) return Boolean; -- 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; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Permissions.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
Fix comment style for dynamo
Fix comment style for dynamo
Ada
apache-2.0
Letractively/ada-security
6285c8c2693ff53a8c2c9753701647d24f9dc762
src/atlas-server.adb
src/atlas-server.adb
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with AWS.Net.SSL; with AWS.Config.Set; with ASF.Server.Web; with AWA.Setup.Applications; with Atlas.Applications; procedure Atlas.Server is procedure Configure (Config : in out AWS.Config.Object); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : ASF.Server.Web.AWS_Container; procedure Setup is new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class, Atlas.Applications.Application_Access, Atlas.Applications.Initialize); procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Input_Line_Size_Limit (1_000_000); AWS.Config.Set.Max_Connection (Config, 2); AWS.Config.Set.Accept_Queue_Size (Config, 100); AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024); AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000); end Configure; begin WS.Configure (Configure'Access); WS.Start; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH); delay 365.0 * 24.0 * 3600.0; App.Close; exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with AWS.Net.SSL; with AWS.Config.Set; with ASF.Server.Web; with AWA.Setup.Applications; with Atlas.Applications; procedure Atlas.Server is procedure Configure (Config : in out AWS.Config.Object); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : ASF.Server.Web.AWS_Container; procedure Setup is new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class, Atlas.Applications.Application_Access, Atlas.Applications.Initialize); procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Input_Line_Size_Limit (1_000_000); AWS.Config.Set.Max_Connection (Config, 2); AWS.Config.Set.Accept_Queue_Size (Config, 100); AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024); AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000); end Configure; begin WS.Configure (Configure'Access); WS.Start; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; delay 365.0 * 24.0 * 3600.0; App.Close; exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
Check for SSL support after the Setup so that the logger is initialized
Check for SSL support after the Setup so that the logger is initialized
Ada
apache-2.0
stcarrez/atlas
7f86efea00791d748c0065ba6542bc1621532737
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Value'Length); end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Value'Length); end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3c0697ea44db2a40d9784c9ce8f664d389986f93
src/wiki-streams-html.ads
src/wiki-streams-html.ads
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream_Type is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream_Type'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Writer_Type'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream_Type is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream_Type'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Writer_Type'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
Use Wiki.Strings.WString type for the Write_Wide_Element procedure
Use Wiki.Strings.WString type for the Write_Wide_Element procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
95b97ee5993616cedff48465d224e07142b57c75
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- Copyright (C) 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with DOM.Core; with Util.Log; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface and Util.Log.Logging; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String; Arg2 : in String := "") is abstract; -- Get the config directory path. function Get_Config_Directory (Handler : in Generator) return String is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in Boolean := False) return Boolean is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode; Mapping : in String) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled 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. 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. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- Copyright (C) 2011, 2012, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with DOM.Core; with Util.Log; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface and Util.Log.Logging; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String; Arg2 : in String := "") is abstract; -- Get the config directory path. function Get_Config_Directory (Handler : in Generator) return String is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in Boolean := False) return Boolean is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode; Mapping : in String) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled 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. 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. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
Fix #9: add a Project parameter to Prepare
Fix #9: add a Project parameter to Prepare
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
e94ac85cce0fa13f5f1ebadc8e32b50905040cce
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "98"; copyright_years : constant String := "2015-2018"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.3.0"; previous_compiler : constant String := "7.2.0"; binutils_version : constant String := "2.30"; previous_binutils : constant String := "2.29.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "99"; copyright_years : constant String := "2015-2018"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.3.0"; previous_compiler : constant String := "7.2.0"; binutils_version : constant String := "2.30"; previous_binutils : constant String := "2.29.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump version
Bump version The ravensource only requires 0.98 to work, but let's bump the version to reflect recent work including GITHUB_PRIV support.
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
f7031e582d729d6bf57c2c28a86f9b853167c008
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "21"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "22"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Upgrade version 1.21 => 1.22
ports-mgmt/synth: Upgrade version 1.21 => 1.22 Two minor bug fixes: * A specific check during test mode would emit a failure to stdout when testing devel/py-setuptools27. It turns out that there's a file there with a space in the filename. The filename was an argument for /usr/bin//file and it wasn't escaped. The file in question had parentheses too which the shell was trying to process. The fix was to escape the filename in the /usr/bin/file command. * The builders were mounting the source directory from "/usr/src", not $sysroot/usr/src as intended. This potentially causes breakage when the $sysroot reflects a different versions/release than the host machine has (e.g. making FreeBSD 10.2 packages on FreeBSD 11-current). Now the source directory mount is relative to profile's $sysroot.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
48cb00b77c703392c7c5675bf1b3e5826df09a8b
src/asf-views-nodes-jsf.adb
src/asf-views-nodes-jsf.adb
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- Create the Converter Tag -- ------------------------------ function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Validator Tag -- ------------------------------ function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. -- ------------------------------ function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- Create the Attribute Tag -- ------------------------------ function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- Create the Facet Tag -- ------------------------------ function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. -- ------------------------------ overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is begin null; end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- Create the Metadata Tag -- ------------------------------ function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. -- ------------------------------ overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- 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.Beans.Objects; with ASF.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- Create the Converter Tag -- ------------------------------ function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Validator Tag -- ------------------------------ function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. -- ------------------------------ function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- Create the Attribute Tag -- ------------------------------ function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- Create the Facet Tag -- ------------------------------ function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. -- ------------------------------ overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is Facet : constant UIComponent_Access := new UIComponent; Name : constant Util.Beans.Objects.Object := Get_Value (Node.Facet_Name.all, Context); begin Node.Build_Children (Facet, Context); Parent.Add_Facet (Util.Beans.Objects.To_String (Name), Facet.all'Access, Node); end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- Create the Metadata Tag -- ------------------------------ function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. -- ------------------------------ overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; end ASF.Views.Nodes.Jsf;
Fix implementation of <f:facet> to build the facet tree component and associate it with the parent component under the given facet name
Fix implementation of <f:facet> to build the facet tree component and associate it with the parent component under the given facet name
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2c5325647acff6904490f54e49d085142ef37eec
src/util-encoders.adb
src/util-encoders.adb
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- 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.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Encoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Last : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); begin Free (E.Encode); Free (E.Decode); end Finalize; end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 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 Ada.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Encoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Last : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ procedure Transform (E : in Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Pos : Natural := Data'First; First : Streams.Stream_Element_Offset := Into'First; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in the output data array. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Into (First .. Into'Last), Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < First then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; First := Last; Pos := Next_Pos; end; end loop; end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); begin Free (E.Encode); Free (E.Decode); end Finalize; end Util.Encoders;
Implement new Transform procedure that gets a String as input data, transform that into some stream element array and calls the transform encoder operation
Implement new Transform procedure that gets a String as input data, transform that into some stream element array and calls the transform encoder operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8bcb2a0be158d04f6c4bf490244099eae6323964
regtests/asf-applications-main-tests.adb
regtests/asf-applications-main-tests.adb
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin T.App.Read_Configuration (Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); T.App.Read_Configuration (Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; end ASF.Applications.Main.Tests;
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; end ASF.Applications.Main.Tests;
Fix compilation of unit test
Fix compilation of unit test
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
d1603277f52d56c057a47ab6edd8c9f1497d042a
src/asf-contexts-writer.adb
src/asf-contexts-writer.adb
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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 Unicode; package body ASF.Contexts.Writer is use Unicode; procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character); -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out ResponseWriter'Class); -- ------------------------------ -- Response Writer -- ------------------------------ -- ------------------------------ -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out ResponseWriter; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream) is begin Stream.Initialize (Output); Stream.Content_Type := To_Unbounded_String (Content_Type); Stream.Encoding := Unicode.Encodings.Get_By_Name (Encoding); end Initialize; -- ------------------------------ -- Flush the response stream and release the buffer. -- ------------------------------ procedure Finalize (Object : in out ResponseWriter) is begin Object.Flush; end Finalize; -- ------------------------------ -- Get the content type. -- ------------------------------ function Get_Content_Type (Stream : in ResponseWriter) return String is begin return To_String (Stream.Content_Type); end Get_Content_Type; -- ------------------------------ -- Get the character encoding. -- ------------------------------ function Get_Encoding (Stream : in ResponseWriter) return String is begin return Stream.Encoding.Name.all; end Get_Encoding; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out ResponseWriter'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Close_Start := True; end Start_Element; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Optional_Element (1 .. Name'Length) := Name; Stream.Optional_Element_Size := Name'Length; end Start_Optional_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); if Stream.Optional_Element_Written then Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end if; Stream.Optional_Element_Written := False; Stream.Optional_Element_Size := 0; end End_Optional_Element; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ procedure Write_Element (Stream : in out ResponseWriter; Name : in String; Content : in String) is begin Stream.Start_Element (Name); Stream.Write_Text (Content); Stream.End_Element (Name); end Write_Element; procedure Write_Wide_Element (Stream : in out ResponseWriter; Name : in String; Content : in Wide_Wide_String) is begin Stream.Start_Element (Name); Stream.Write_Wide_Text (Content); Stream.End_Element (Name); end Write_Wide_Element; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in String) is begin -- If we have an optional element, start it. if Stream.Optional_Element_Size > 0 and not Stream.Optional_Element_Written then Stream.Write ('<'); Stream.Write (Stream.Optional_Element (1 .. Stream.Optional_Element_Size)); Stream.Close_Start := True; Stream.Optional_Element_Written := True; end if; if Stream.Close_Start then Stream.Write (' '); Stream.Write (Name); Stream.Write ('='); Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("&quot;"); else Stream.Write_Escape (C); end if; end; end loop; Stream.Write ('"'); end if; end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in Unbounded_String) is begin Stream.Write_Attribute (Name, To_String (Value)); end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in EL.Objects.Object) is S : constant String := EL.Objects.To_String (Value); begin Stream.Write_Attribute (Name, S); end Write_Attribute; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ procedure Write_Text (Stream : in out ResponseWriter; Text : in String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Char (Text (I)); end loop; end Write_Text; procedure Write_Text (Stream : in out ResponseWriter; Text : in Unbounded_String) is Count : constant Natural := Length (Text); begin if Count > 0 then for I in 1 .. Count loop ResponseWriter'Class (Stream).Write_Char (Element (Text, I)); end loop; end if; end Write_Text; procedure Write_Wide_Text (Stream : in out ResponseWriter; Text : in Wide_Wide_String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Wide_Char (Text (I)); end loop; end Write_Wide_Text; procedure Write_Text (Stream : in out ResponseWriter; Value : in EL.Objects.Object) is use EL.Objects; Of_Type : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); begin case Of_Type is when TYPE_BOOLEAN => Close_Current (Stream); if To_Boolean (Value) then ResponseWriter'Class (Stream).Write ("true"); else ResponseWriter'Class (Stream).Write ("false"); end if; when TYPE_INTEGER | TYPE_FLOAT => Close_Current (Stream); ResponseWriter'Class (Stream).Write (To_String (Value)); when TYPE_STRING => ResponseWriter'Class (Stream).Write_Text (To_String (Value)); when others => ResponseWriter'Class (Stream).Write_Wide_Text (To_Wide_Wide_String (Value)); end case; end Write_Text; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Char (Stream : in out ResponseWriter; Char : in Character) is begin Close_Current (Stream); Write_Escape (Stream, Char); end Write_Char; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character) is Code : constant Unicode_Char := Character'Pos (Char); begin -- Tilde or less... if Code < 16#A0# then -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Escape; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Wide_Char (Stream : in out ResponseWriter; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin Close_Current (Stream); -- Tilde or less... if Code < 16#100# then Stream.Write_Char (Character'Val (Code)); else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Wide_Char; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out ResponseWriter; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Close_Current (Stream); ASF.Streams.Print_Stream (Stream).Write (Item); end Write; end ASF.Contexts.Writer;
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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 Unicode; package body ASF.Contexts.Writer is use Unicode; procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character); -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out ResponseWriter'Class); -- ------------------------------ -- Response Writer -- ------------------------------ -- ------------------------------ -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out ResponseWriter; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream) is begin Stream.Initialize (Output); Stream.Content_Type := To_Unbounded_String (Content_Type); Stream.Encoding := Unicode.Encodings.Get_By_Name (Encoding); end Initialize; -- ------------------------------ -- Flush the response stream and release the buffer. -- ------------------------------ procedure Finalize (Object : in out ResponseWriter) is begin Object.Flush; end Finalize; -- ------------------------------ -- Get the content type. -- ------------------------------ function Get_Content_Type (Stream : in ResponseWriter) return String is begin return To_String (Stream.Content_Type); end Get_Content_Type; -- ------------------------------ -- Get the character encoding. -- ------------------------------ function Get_Encoding (Stream : in ResponseWriter) return String is begin return Stream.Encoding.Name.all; end Get_Encoding; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out ResponseWriter'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Close_Start := True; end Start_Element; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Optional_Element (1 .. Name'Length) := Name; Stream.Optional_Element_Size := Name'Length; end Start_Optional_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); if Stream.Optional_Element_Written then Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end if; Stream.Optional_Element_Written := False; Stream.Optional_Element_Size := 0; end End_Optional_Element; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ procedure Write_Element (Stream : in out ResponseWriter; Name : in String; Content : in String) is begin Stream.Start_Element (Name); Stream.Write_Text (Content); Stream.End_Element (Name); end Write_Element; procedure Write_Wide_Element (Stream : in out ResponseWriter; Name : in String; Content : in Wide_Wide_String) is begin Stream.Start_Element (Name); Stream.Write_Wide_Text (Content); Stream.End_Element (Name); end Write_Wide_Element; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in String) is begin -- If we have an optional element, start it. if Stream.Optional_Element_Size > 0 and not Stream.Optional_Element_Written then Stream.Write ('<'); Stream.Write (Stream.Optional_Element (1 .. Stream.Optional_Element_Size)); Stream.Close_Start := True; Stream.Optional_Element_Written := True; end if; if Stream.Close_Start then Stream.Write (' '); Stream.Write (Name); Stream.Write ('='); Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("&quot;"); else Stream.Write_Escape (C); end if; end; end loop; Stream.Write ('"'); end if; end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in Unbounded_String) is begin Stream.Write_Attribute (Name, To_String (Value)); end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in EL.Objects.Object) is S : constant String := EL.Objects.To_String (Value); begin Stream.Write_Attribute (Name, S); end Write_Attribute; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ procedure Write_Text (Stream : in out ResponseWriter; Text : in String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Char (Text (I)); end loop; end Write_Text; procedure Write_Text (Stream : in out ResponseWriter; Text : in Unbounded_String) is Count : constant Natural := Length (Text); begin if Count > 0 then for I in 1 .. Count loop ResponseWriter'Class (Stream).Write_Char (Element (Text, I)); end loop; end if; end Write_Text; procedure Write_Wide_Text (Stream : in out ResponseWriter; Text : in Wide_Wide_String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Wide_Char (Text (I)); end loop; end Write_Wide_Text; procedure Write_Text (Stream : in out ResponseWriter; Value : in EL.Objects.Object) is use EL.Objects; Of_Type : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); begin case Of_Type is when TYPE_BOOLEAN => Close_Current (Stream); if To_Boolean (Value) then ResponseWriter'Class (Stream).Write ("true"); else ResponseWriter'Class (Stream).Write ("false"); end if; when TYPE_INTEGER | TYPE_FLOAT => Close_Current (Stream); ResponseWriter'Class (Stream).Write (To_String (Value)); when TYPE_STRING => ResponseWriter'Class (Stream).Write_Text (To_String (Value)); when others => ResponseWriter'Class (Stream).Write_Wide_Text (To_Wide_Wide_String (Value)); end case; end Write_Text; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Char (Stream : in out ResponseWriter; Char : in Character) is begin Close_Current (Stream); Write_Escape (Stream, Char); end Write_Char; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character) is Code : constant Unicode_Char := Character'Pos (Char); begin -- Tilde or less... -- if Code < 16#A0# then -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; -- else -- declare -- S : String (1 .. 5) := "&#00;"; -- C : Unicode_Char; -- begin -- C := Code and 16#0F#; -- if C > 10 then -- S (4) := Character'Val (C - 10 + Character'Pos ('A')); -- else -- S (4) := Character'Val (C + Character'Pos ('0')); -- end if; -- C := (Code / 16) and 16#0F#; -- if C > 10 then -- S (3) := Character'Val (C - 10 + Character'Pos ('A')); -- else -- S (3) := Character'Val (C + Character'Pos ('0')); -- end if; -- Stream.Write (S); -- end; -- end if; end Write_Escape; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Wide_Char (Stream : in out ResponseWriter; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin Close_Current (Stream); -- Tilde or less... if Code < 16#100# then Stream.Write_Char (Character'Val (Code)); else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Wide_Char; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out ResponseWriter; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Close_Current (Stream); ASF.Streams.Print_Stream (Stream).Write (Item); end Write; end ASF.Contexts.Writer;
Write the character above 0xA0 as is. This allows to have UTF-8 sequences in a String and generate UTF-8 pages.
Write the character above 0xA0 as is. This allows to have UTF-8 sequences in a String and generate UTF-8 pages.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f84be45c60ca72a8ab0abd9ffdf4c5da14a4ba46
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Filter_Type; Level : in Natural) is begin Document.Document.Add_Blockquote (Level); end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean) is begin Document.Document.Add_List_Item (Level, Ordered); end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type) is begin if Filter.Next /= null then Filter.Next.Finish; end if; end Finish; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Wiki.Nodes.Append (Document, Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Nodes.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Nodes.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Wiki.Nodes.Push_Node (Document, Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Wiki.Nodes.Pop_Node (Document, Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Wiki.Nodes.Add_Blockquote (Document, Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Wiki.Nodes.Add_List_Item (Document, Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Wiki.Nodes.Add_Link (Document, Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Wiki.Nodes.Add_Image (Document, Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Wiki.Nodes.Add_Quote (Document, Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Wiki.Nodes.Add_Preformatted (Document, Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type) is begin if Filter.Next /= null then Filter.Next.Finish; end if; end Finish; end Wiki.Filters;
Update Add_Blockquote and Add_List_Item procedures
Update Add_Blockquote and Add_List_Item procedures
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
8715b652b7a7eb858b3371c5036ac1b713120cf8
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; -- The <b>AWA.Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; -- The <b>AWA.Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; end Wiki.Parsers;
Add the Markdown syntax
Add the Markdown syntax
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki