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
69dbe2bca43a484480902df5cff05af25a2bbca0
matp/src/memory/mat-memory-targets.adb
matp/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map) is begin Memory.Memory.Find (From, To, Into); end Find; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot, Old_Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map) is Iter : Region_Info_Cursor; begin Iter := Regions.Ceiling (From); while Region_Info_Maps.Has_Element (Iter) loop declare Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter); Region : Region_Info; begin exit when Start > To; Region := Region_Info_Maps.Element (Iter); if Region.End_Addr >= From then if not Into.Contains (Start) then Into.Insert (Start, Region); end if; end if; Region_Info_Maps.Next (Iter); end; end loop; end Find; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); Slot.Size := Item.Size; if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Iter := Freed_Slots.Find (Addr); if not Allocation_Maps.Has_Element (Iter) then Freed_Slots.Insert (Addr, Item); end if; end if; exception when others => Log.Error ("Free {0} raised some exception", MAT.Types.Hex_Image (Addr)); raise; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Old_Size := Element.Size; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Old_Size := 0; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Old_Size := Allocation_Maps.Element (Pos).Size; Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map) is begin Memory.Memory.Find (From, To, Into); end Find; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot, Old_Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map) is Iter : Region_Info_Cursor; begin Iter := Regions.Ceiling (From); while Region_Info_Maps.Has_Element (Iter) loop declare Start : constant MAT.Types.Target_Addr := Region_Info_Maps.Key (Iter); Region : Region_Info; begin exit when Start > To; Region := Region_Info_Maps.Element (Iter); if Region.End_Addr >= From then if not Into.Contains (Start) then Into.Insert (Start, Region); end if; end if; Region_Info_Maps.Next (Iter); end; end loop; end Find; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in out Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); Slot.Size := Item.Size; if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Iter := Freed_Slots.Find (Addr); if not Allocation_Maps.Has_Element (Iter) then Freed_Slots.Insert (Addr, Item); end if; end if; exception when others => Log.Error ("Free {0} raised some exception", MAT.Types.Hex_Image (Addr)); raise; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Old_Size := Element.Size; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Old_Size := 0; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Old_Size := Allocation_Maps.Element (Pos).Size; Stats.Total_Alloc := Stats.Total_Alloc - Old_Size; Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; Result.Used_Count := Natural (Used_Slots.Length); end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Add the number of allocated memory slots in the Stat_Information report
Add the number of allocated memory slots in the Stat_Information report
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9ab0923a5ffa4400a9f210f37db24daad2d23ee9
src/asf-factory.ads
src/asf-factory.ads
----------------------------------------------------------------------- -- asf-factory -- Component and tag factory -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Views.Nodes; with ASF.Converters; with ASF.Validators; with EL.Objects; private with Util.Beans.Objects.Hash; private with Ada.Containers; private with Ada.Containers.Hashed_Maps; -- The <b>ASF.Factory</b> is the main factory for building the facelet -- node tree and defining associated component factory. A binding library -- must be registered before the application starts. The binding library -- must not be changed (this is a read-only static definition of names -- associated with create functions). package ASF.Factory is use ASF; Unknown_Name : exception; -- Binding name type Name_Access is new Util.Strings.Name_Access; -- ------------------------------ -- Binding definition. -- ------------------------------ -- The binding links an XHTML entity name to a tag node implementation -- and a component creation handler. When the XHTML entity is found, -- the associated binding is search and when found the node is created -- by using the <b>Tag</b> create function. type Binding is record Name : Name_Access; Component : ASF.Views.Nodes.Create_Access; Tag : ASF.Views.Nodes.Tag_Node_Create_Access; end record; -- ------------------------------ -- List of bindings -- ------------------------------ -- The binding array defines a set of XML entity names that represent -- a library accessible through a XML name-space. The binding array -- must be sorted on the binding name. The <b>Check</b> procedure will -- verify this assumption when the bindings are registered in the factory. type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access constant Binding_Array; type Factory_Bindings is record URI : Name_Access; Bindings : Binding_Array_Access; end record; type Factory_Bindings_Access is access constant Factory_Bindings; -- Find the create function associated with the name. -- Returns null if there is no binding associated with the name. function Find (Factory : Factory_Bindings; Name : String) return Binding; -- Check the definition of the component factory. procedure Check (Factory : in Factory_Bindings); -- ------------------------------ -- Component Factory -- ------------------------------ -- The <b>Component_Factory</b> is the main entry point to register bindings -- and resolve them when an XML file is read. type Component_Factory is limited private; -- Register a binding library in the factory. procedure Register (Factory : in out Component_Factory; Bindings : in Factory_Bindings_Access); -- Find the create function in bound to the name in the given URI name-space. -- Returns null if no such binding exist. function Find (Factory : Component_Factory; URI : String; Name : String) return Binding; -- ------------------------------ -- Converter Factory -- ------------------------------ -- The <b>Converter_Factory</b> registers the converters which can be used -- to convert a value into a string or the opposite. -- Register the converter instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- ------------------------------ -- Validator Factory -- ------------------------------ -- Register the validator instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Validator : in ASF.Validators.Validator_Access); -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; private use Util.Strings; use ASF.Converters; use ASF.Validators; -- Tag library map indexed on the library namespace. package Factory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Name_Access, Element_Type => Factory_Bindings_Access, Hash => Hash, Equivalent_Keys => Equivalent_Keys); -- Converter map indexed on the converter name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a converter. package Converter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Converter_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); -- Validator map indexed on the validator name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a validator. package Validator_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Validator_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); type Component_Factory is limited record Map : Factory_Maps.Map; Converters : Converter_Maps.Map; Validators : Validator_Maps.Map; end record; end ASF.Factory;
----------------------------------------------------------------------- -- asf-factory -- Component and tag factory -- 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 ASF.Views.Nodes; with ASF.Converters; with ASF.Validators; with EL.Objects; private with Util.Beans.Objects.Hash; private with Ada.Containers; private with Ada.Containers.Hashed_Maps; -- The <b>ASF.Factory</b> is the main factory for building the facelet -- node tree and defining associated component factory. A binding library -- must be registered before the application starts. The binding library -- must not be changed (this is a read-only static definition of names -- associated with create functions). package ASF.Factory is use ASF; -- ------------------------------ -- List of bindings -- ------------------------------ -- The binding array defines a set of XML entity names that represent -- a library accessible through a XML name-space. The binding array -- must be sorted on the binding name. The <b>Check</b> procedure will -- verify this assumption when the bindings are registered in the factory. type Binding_Array is array (Natural range <>) of aliased ASF.Views.Nodes.Binding; type Binding_Array_Access is access constant Binding_Array; type Factory_Bindings is limited record URI : ASF.Views.Nodes.Name_Access; Bindings : Binding_Array_Access; end record; type Factory_Bindings_Access is access constant Factory_Bindings; -- ------------------------------ -- Component Factory -- ------------------------------ -- The <b>Component_Factory</b> is the main entry point to register bindings -- and resolve them when an XML file is read. type Component_Factory is limited private; -- Register a binding library in the factory. procedure Register (Factory : in out Component_Factory; Bindings : in Factory_Bindings_Access); -- Find the create function in bound to the name in the given URI name-space. -- Returns null if no such binding exist. function Find (Factory : in Component_Factory; URI : in String; Name : in String) return ASF.Views.Nodes.Binding_Access; -- ------------------------------ -- Converter Factory -- ------------------------------ -- The <b>Converter_Factory</b> registers the converters which can be used -- to convert a value into a string or the opposite. -- Register the converter instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- ------------------------------ -- Validator Factory -- ------------------------------ -- Register the validator instance under the given name. procedure Register (Factory : in out Component_Factory; Name : in String; Validator : in ASF.Validators.Validator_Access); -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find (Factory : in Component_Factory; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; private use ASF.Converters; use ASF.Validators; use ASF.Views.Nodes; -- The tag name defines a URI with the name. type Tag_Name is record URI : ASF.Views.Nodes.Name_Access; Name : ASF.Views.Nodes.Name_Access; end record; -- Compute a hash for the tag name. function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type; -- Returns true if both tag names are identical. function "=" (Left, Right : in Tag_Name) return Boolean; -- Tag library map indexed on the library namespace. package Factory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Tag_Name, Element_Type => Binding_Access, Hash => Hash, Equivalent_Keys => "="); -- Converter map indexed on the converter name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a converter. package Converter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Converter_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); -- Validator map indexed on the validator name. -- The key is an EL.Objects.Object to minimize the conversions when searching -- for a validator. package Validator_Maps is new Ada.Containers.Hashed_Maps (Key_Type => EL.Objects.Object, Element_Type => Validator_Access, Hash => EL.Objects.Hash, Equivalent_Keys => EL.Objects."="); type Component_Factory is limited record Map : Factory_Maps.Map; Converters : Converter_Maps.Map; Validators : Validator_Maps.Map; end record; end ASF.Factory;
Change the component factory to store each binding and resolve in one search the component binding from the namespace and the name
Change the component factory to store each binding and resolve in one search the component binding from the namespace and the name
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
c63426c6c458a2d553f149edb48c7908785e0085
src/el-beans.ads
src/el-beans.ads
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; end EL.Beans;
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is interface and Readonly_Bean; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Get the element at the given index. function Get_Row (From : List_Bean; Index : Natural) return EL.Objects.Object is abstract; end EL.Beans;
Declare the List_Bean to represent lists that can be accessed from the Object
Declare the List_Bean to represent lists that can be accessed from the Object
Ada
apache-2.0
stcarrez/ada-el
aa012c7459c97b69ce0fb9efae21cf5d846d6498
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; Info.Last_Event := Event; if Event.Index = MAT.Events.MSG_MALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Index = MAT.Events.MSG_REALLOC then Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Alloc_Size + Event.Old_Size; else Info.Free_Size := Info.Alloc_Size + Event.Size; end if; end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > 500_000 then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; end MAT.Events.Timelines;
Fix Update_Size to use the Collect_Info procedure to gather the size statistics
Fix Update_Size to use the Collect_Info procedure to gather the size statistics
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
edb5671ee9791469fb006e8a1175c9f22972ffd5
examples/orka/orka_test-test_9_jobs.adb
examples/orka/orka_test-test_9_jobs.adb
-- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Real_Time; with Ada.Text_IO; with Orka.Futures; with Orka.Jobs; with Orka_Test.Package_9_Jobs; procedure Orka_Test.Test_9_Jobs is Job_0 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 0); Job_1 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 1); Job_2 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 2); Job_3 : constant Orka.Jobs.Parallel_Job_Ptr := new Package_9_Jobs.Test_Parallel_Job; Job_4 : constant Orka.Jobs.Job_Ptr := Orka.Jobs.Parallelize (Job_3, 24, 6); Future : Orka.Futures.Pointers.Mutable_Pointer; Status : Orka.Futures.Status; use Ada.Real_Time; use Ada.Text_IO; T1, T2 : Time; package Boss renames Package_9_Jobs.Boss; begin -- Graph: Job_0 --> Job_1 --> Job_4 (4 slices) --> Job_2 Job_1.Set_Dependencies ((1 => Job_0)); Job_4.Set_Dependencies ((1 => Job_1)); Job_2.Set_Dependencies ((1 => Job_4)); Package_9_Jobs.Boss.Queue.Enqueue (Job_0, Future); Put_Line ("References (2): " & Future.References'Image); T1 := Clock; declare Reference : Orka.Futures.Pointers.Reference := Future.Get; Future : constant Orka.Futures.Future_Access := Reference.Value; begin select Future.Wait_Until_Done (Status); T2 := Clock; Put_Line (" Status: " & Status'Image); Put_Line (" Time: " & Duration'Image (1e3 * To_Duration (T2 - T1)) & " ms"); or delay until Clock + Milliseconds (10); Put_Line (" Time out: " & Reference.Current_Status'Image); end select; end; Put_Line ("References (1): " & Future.References'Image); Boss.Shutdown; Put_Line ("CPU Queue: " & Boss.Queue.Length (Boss.Queues.CPU)'Image); Put_Line ("GPU Queue: " & Boss.Queue.Length (Boss.Queues.GPU)'Image); end Orka_Test.Test_9_Jobs;
-- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Exceptions; with Ada.Real_Time; with Ada.Text_IO; with Orka.Futures; with Orka.Jobs; with Orka_Test.Package_9_Jobs; procedure Orka_Test.Test_9_Jobs is Job_0 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 0); Job_1 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 1); Job_2 : constant Orka.Jobs.Job_Ptr := new Package_9_Jobs.Test_Sequential_Job' (Orka.Jobs.Abstract_Job with ID => 2); Job_3 : constant Orka.Jobs.Parallel_Job_Ptr := new Package_9_Jobs.Test_Parallel_Job; Job_4 : constant Orka.Jobs.Job_Ptr := Orka.Jobs.Parallelize (Job_3, 24, 6); Handle : Orka.Futures.Pointers.Mutable_Pointer; Status : Orka.Futures.Status; use Ada.Exceptions; use Ada.Real_Time; use Ada.Text_IO; T1, T2 : Time; package Boss renames Package_9_Jobs.Boss; begin -- Graph: Job_0 --> Job_1 --> Job_4 (4 slices) --> Job_2 Orka.Jobs.Chain ((Job_0, Job_1, Job_4, Job_2)); Package_9_Jobs.Boss.Queue.Enqueue (Job_0, Handle); Put_Line ("References (2): " & Handle.References'Image); T1 := Clock; declare Reference : constant Orka.Futures.Pointers.Reference := Handle.Get; Future : constant Orka.Futures.Future_Access := Reference.Value; begin select Future.Wait_Until_Done (Status); T2 := Clock; Put_Line (" Status: " & Status'Image); Put_Line (" Time: " & Duration'Image (1e3 * To_Duration (T2 - T1)) & " ms"); or delay until T1 + Milliseconds (10); Put_Line (" Time out: " & Reference.Current_Status'Image); end select; exception when Error : others => Put_Line ("Error: " & Exception_Information (Error)); end; Put_Line ("References (1): " & Handle.References'Image); Boss.Shutdown; Put_Line ("CPU Queue: " & Boss.Queue.Length (Boss.Queues.CPU)'Image); Put_Line ("GPU Queue: " & Boss.Queue.Length (Boss.Queues.GPU)'Image); end Orka_Test.Test_9_Jobs;
Use Orka.Jobs.Chain in job graph example
examples: Use Orka.Jobs.Chain in job graph example Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
7e0f95846c2ca73f0b9a62ccc95cc62e3c7d71eb
samples/auth_cb.adb
samples/auth_cb.adb
----------------------------------------------------------------------- -- auth_cb -- Authentication callback examples -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with AWS.Session; with AWS.Messages; with AWS.Templates; with AWS.Services.Web_Block.Registry; with Util.Log.Loggers; package body Auth_CB is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Auth_CB"); -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; USER_INFO_ATTRIBUTE : constant String := "user-info"; Null_Association : Security.Auth.Association; Null_Auth : Security.Auth.Authentication; package Auth_Session is new AWS.Session.Generic_Data (Security.Auth.Association, Null_Association); package User_Session is new AWS.Session.Generic_Data (Security.Auth.Authentication, Null_Auth); overriding function Get_Parameter (Params : in Auth_Config; Name : in String) return String is begin if Params.Exists (Name) then return Params.Get (Name); else return ""; end if; end Get_Parameter; function Get_Auth_Name (Request : in AWS.Status.Data) return String is URI : constant String := AWS.Status.URI (Request); Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "/", Ada.Strings.Backward); begin if Pos = 0 then return ""; else Log.Info ("OpenID authentication with {0}", URI); return URI (Pos + 1 .. URI'Last); end if; end Get_Auth_Name; -- ------------------------------ -- Implement the first step of authentication: discover the OpenID (if any) provider, -- create the authorization request and redirect the user to the authorization server. -- Some authorization data is saved in the session for the verify process. -- ------------------------------ function Get_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is Name : constant String := Get_Auth_Name (Request); Provider : constant String := Config.Get_Parameter ("auth.provider." & Name); URL : constant String := Config.Get_Parameter ("auth.url." & Name); Mgr : Security.Auth.Manager; OP : Security.Auth.End_Point; Assoc : Security.Auth.Association; begin if URL'Length = 0 or Provider'Length = 0 then return AWS.Response.URL (Location => "/login.html"); end if; Mgr.Initialize (Config, Provider); -- Yadis discovery (get the XRDS file). This step does nothing for OAuth. Mgr.Discover (URL, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc); SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Auth_Session.Set (SID, OPENID_ASSOC_ATTRIBUTE, Assoc); return AWS.Response.URL (Location => Auth_URL); end; end Get_Authorization; -- ------------------------------ -- Second step of authentication: verify the authorization response. The authorization -- data saved in the session is extracted and checked against the response. If it matches -- the response is verified to check if the authentication succeeded or not. -- The user is then redirected to the success page. -- ------------------------------ function Verify_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is use type Security.Auth.Auth_Result; -- Give access to the request parameters. type Auth_Params is limited new Security.Auth.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return AWS.Status.Parameter (Request, Name); end Get_Parameter; Mgr : Security.Auth.Manager; Assoc : Security.Auth.Association; Credential : Security.Auth.Authentication; Params : Auth_Params; SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Verify openid authentication"); if not AWS.Session.Exist (SID, OPENID_ASSOC_ATTRIBUTE) then Log.Warn ("Session has expired during OpenID authentication process"); return AWS.Response.Build ("text/html", "Session has expired", AWS.Messages.S403); end if; Assoc := Auth_Session.Get (SID, OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. AWS.Session.Remove (SID, OPENID_ASSOC_ATTRIBUTE); Mgr.Initialize (Provider => Security.Auth.Get_Provider (Assoc), Params => Config); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc, Params, Credential); if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then Log.Info ("Authentication has failed"); return AWS.Response.Build ("text/html", "Authentication failed", AWS.Messages.S403); end if; Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Claimed id: {0}", Security.Auth.Get_Claimed_Id (Credential)); Log.Info ("Email: {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Name: {0}", Security.Auth.Get_Full_Name (Credential)); -- Save the user information in the session (for the purpose of this demo). User_Session.Set (SID, USER_INFO_ATTRIBUTE, Credential); declare URL : constant String := Config.Get_Parameter ("openid.success_url"); begin Log.Info ("Redirect user to success URL: {0}", URL); return AWS.Response.URL (Location => URL); end; end Verify_Authorization; function User_Info (Request : in AWS.Status.Data) return AWS.Response.Data is URI : constant String := AWS.Status.URI (Request); SID : constant AWS.Session.Id := AWS.Status.Session (Request); Credential : Security.Auth.Authentication; Set : AWS.Templates.Translate_Set; begin if AWS.Session.Exist (SID, USER_INFO_ATTRIBUTE) then Credential := User_Session.Get (SID, USER_INFO_ATTRIBUTE); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("ID", Security.Auth.Get_Claimed_Id (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("EMAIL", Security.Auth.Get_Email (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("NAME", Security.Auth.Get_Full_Name (Credential))); end if; return AWS.Services.Web_Block.Registry.Build ("success", Request, Set); end User_Info; end Auth_CB;
----------------------------------------------------------------------- -- auth_cb -- Authentication callback examples -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with AWS.Session; with AWS.Messages; with AWS.Templates; with AWS.Services.Web_Block.Registry; with Util.Log.Loggers; package body Auth_CB is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Auth_CB"); -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; USER_INFO_ATTRIBUTE : constant String := "user-info"; Null_Association : Security.Auth.Association; Null_Auth : Security.Auth.Authentication; package Auth_Session is new AWS.Session.Generic_Data (Security.Auth.Association, Null_Association); package User_Session is new AWS.Session.Generic_Data (Security.Auth.Authentication, Null_Auth); overriding function Get_Parameter (Params : in Auth_Config; Name : in String) return String is begin if Params.Exists (Name) then return Params.Get (Name); else return ""; end if; end Get_Parameter; function Get_Auth_Name (Request : in AWS.Status.Data) return String is URI : constant String := AWS.Status.URI (Request); Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "/", Ada.Strings.Backward); begin if Pos = 0 then return ""; else Log.Info ("OpenID authentication with {0}", URI); return URI (Pos + 1 .. URI'Last); end if; end Get_Auth_Name; -- ------------------------------ -- Implement the first step of authentication: discover the OpenID (if any) provider, -- create the authorization request and redirect the user to the authorization server. -- Some authorization data is saved in the session for the verify process. -- ------------------------------ function Get_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is Name : constant String := Get_Auth_Name (Request); URL : constant String := Config.Get_Parameter ("auth.url." & Name); Mgr : Security.Auth.Manager; OP : Security.Auth.End_Point; Assoc : Security.Auth.Association; begin if URL'Length = 0 or Name'Length = 0 then return AWS.Response.URL (Location => "/login.html"); end if; Mgr.Initialize (Config, Name); -- Yadis discovery (get the XRDS file). This step does nothing for OAuth. Mgr.Discover (URL, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc); SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Auth_Session.Set (SID, OPENID_ASSOC_ATTRIBUTE, Assoc); return AWS.Response.URL (Location => Auth_URL); end; end Get_Authorization; -- ------------------------------ -- Second step of authentication: verify the authorization response. The authorization -- data saved in the session is extracted and checked against the response. If it matches -- the response is verified to check if the authentication succeeded or not. -- The user is then redirected to the success page. -- ------------------------------ function Verify_Authorization (Request : in AWS.Status.Data) return AWS.Response.Data is use type Security.Auth.Auth_Result; -- Give access to the request parameters. type Auth_Params is limited new Security.Auth.Parameters with null record; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String; overriding function Get_Parameter (Params : in Auth_Params; Name : in String) return String is pragma Unreferenced (Params); begin return AWS.Status.Parameter (Request, Name); end Get_Parameter; Mgr : Security.Auth.Manager; Assoc : Security.Auth.Association; Credential : Security.Auth.Authentication; Params : Auth_Params; SID : constant AWS.Session.Id := AWS.Status.Session (Request); begin Log.Info ("Verify openid authentication"); if not AWS.Session.Exist (SID, OPENID_ASSOC_ATTRIBUTE) then Log.Warn ("Session has expired during OpenID authentication process"); return AWS.Response.Build ("text/html", "Session has expired", AWS.Messages.S403); end if; Assoc := Auth_Session.Get (SID, OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. AWS.Session.Remove (SID, OPENID_ASSOC_ATTRIBUTE); Mgr.Initialize (Name => Security.Auth.Get_Provider (Assoc), Params => Config); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc, Params, Credential); if Security.Auth.Get_Status (Credential) /= Security.Auth.AUTHENTICATED then Log.Info ("Authentication has failed"); return AWS.Response.Build ("text/html", "Authentication failed", AWS.Messages.S403); end if; Log.Info ("Authentication succeeded for {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Claimed id: {0}", Security.Auth.Get_Claimed_Id (Credential)); Log.Info ("Email: {0}", Security.Auth.Get_Email (Credential)); Log.Info ("Name: {0}", Security.Auth.Get_Full_Name (Credential)); -- Save the user information in the session (for the purpose of this demo). User_Session.Set (SID, USER_INFO_ATTRIBUTE, Credential); declare URL : constant String := Config.Get_Parameter ("openid.success_url"); begin Log.Info ("Redirect user to success URL: {0}", URL); return AWS.Response.URL (Location => URL); end; end Verify_Authorization; function User_Info (Request : in AWS.Status.Data) return AWS.Response.Data is URI : constant String := AWS.Status.URI (Request); SID : constant AWS.Session.Id := AWS.Status.Session (Request); Credential : Security.Auth.Authentication; Set : AWS.Templates.Translate_Set; begin if AWS.Session.Exist (SID, USER_INFO_ATTRIBUTE) then Credential := User_Session.Get (SID, USER_INFO_ATTRIBUTE); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("ID", Security.Auth.Get_Claimed_Id (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("EMAIL", Security.Auth.Get_Email (Credential))); AWS.Templates.Insert (Set, AWS.Templates.Assoc ("NAME", Security.Auth.Get_Full_Name (Credential))); end if; return AWS.Services.Web_Block.Registry.Build ("success", Request, Set); end User_Info; end Auth_CB;
Fix initialization
Fix initialization
Ada
apache-2.0
stcarrez/ada-security
d3555d3ce5b161b6cd0a5561c1ed576de5c63988
regtests/util-events-channels-tests.adb
regtests/util-events-channels-tests.adb
----------------------------------------------------------------------- -- events.tests -- Unit tests for event channels -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Events.Channels.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Events.Channels"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event", Test_Post_Event'Access); end Add_Tests; procedure Receive_Event (Sub : in out Test; Item : in Event'Class) is pragma Unreferenced (Item); begin Sub.Count := Sub.Count + 1; end Receive_Event; procedure Test_Post_Event (T : in out Test) is C : constant Channel_Access := Create ("test", "direct"); E : Event; T1 : aliased Test; T2 : aliased Test; begin C.Post (E); Assert_Equals (T, "test", C.Get_Name, "Invalid channel name"); C.Subscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 1, T1.Count, "Invalid number of received events"); Assert_Equals (T, 0, T2.Count, "Invalid number of events"); C.Subscribe (T2'Unchecked_Access); C.Post (E); C.Unsubscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 2, T1.Count, "Invalid number of received events"); Assert_Equals (T, 2, T2.Count, "Invalid number of events"); end Test_Post_Event; end Util.Events.Channels.Tests;
----------------------------------------------------------------------- -- events.tests -- Unit tests for event channels -- 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.Test_Caller; package body Util.Events.Channels.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Events.Channels"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Channels.Post_Event", Test_Post_Event'Access); end Add_Tests; procedure Receive_Event (Sub : in out Test; Item : in Event'Class) is pragma Unreferenced (Item); begin Sub.Count := Sub.Count + 1; end Receive_Event; procedure Test_Post_Event (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => Channel'Class, Name => Channel_Access); C : Channel_Access := Create ("test", "direct"); E : Event; T1 : aliased Test; T2 : aliased Test; begin C.Post (E); Assert_Equals (T, "test", C.Get_Name, "Invalid channel name"); C.Subscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 1, T1.Count, "Invalid number of received events"); Assert_Equals (T, 0, T2.Count, "Invalid number of events"); C.Subscribe (T2'Unchecked_Access); C.Post (E); C.Unsubscribe (T1'Unchecked_Access); C.Post (E); Assert_Equals (T, 2, T1.Count, "Invalid number of received events"); Assert_Equals (T, 2, T2.Count, "Invalid number of events"); Free (C); end Test_Post_Event; end Util.Events.Channels.Tests;
Fix memory leak in the unit test
Fix memory leak in the unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0591ebc15be8e247bc5c0b13831117d1a2f7aef2
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK => Image : Boolean; Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; subtype Format_Map is Wiki.Documents.Format_Map; subtype WString is Wide_Wide_String; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_PARAGRAPH, N_HEADER, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_INDENT, N_TEXT, N_LINK); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; -- The possible HTML tags as described in HTML5 specification. type Html_Tag_Type is ( -- Section 4.1 The root element HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag_Type; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT => Level : Natural := 0; Header : WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : WString (1 .. Len); when N_LINK => Image : Boolean; Link_Attr : Wiki.Attributes.Attribute_List_Type; Title : WString (1 .. Len); when N_QUOTE => Quote_Attr : Wiki.Attributes.Attribute_List_Type; Quote : WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag_Type; Attributes : Wiki.Attributes.Attribute_List_Type; Children : Node_List_Access; Parent : Node_Type_Access; when others => null; end case; end record; -- Create a text node. function Create_Text (Text : in WString) return Node_Type_Access; type Document is limited private; -- Append a node to the document. procedure Append (Into : in out Document; Node : in Node_Type_Access); -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type); -- Pop the HTML tag. procedure Pop_Node (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- procedure Add_Text (Doc : in out Document; -- Text : in WString); -- type Renderer is limited interface; -- -- procedure Render (Engine : in out Renderer; -- Doc : in Document; -- Node : in Node_Type) is abstract; -- -- procedure Iterate (Doc : in Document; -- Process : access procedure (Doc : in Document; Node : in Node_Type)) is -- Node : Document_Node_Access := Doc.First; -- begin -- while Node /= null loop -- Process (Doc, Node.Data); -- Node := Node.Next; -- end loop; -- end Iterate; private NODE_LIST_BLOCK_SIZE : constant Positive := 20; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Append a node to the node list. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); type Document is limited record Nodes : Node_List; Current : Node_Type_Access; end record; end Wiki.Nodes;
Declare the Add_Link procedure
Declare the Add_Link procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fe88ba7a5e2b95e03a60947cdb61ad151438034b
mat/src/memory/mat-memory-tools.ads
mat/src/memory/mat-memory-tools.ads
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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; package MAT.Memory.Tools is type Size_Info_Type is record Count : Natural; end record; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes for the memory slots in the map. procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map); end MAT.Memory.Tools;
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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.Expressions; package MAT.Memory.Tools is type Size_Info_Type is record Count : Natural; end record; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes for the memory slots in the map. procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); end MAT.Memory.Tools;
Add a filter expression to the Find procedure
Add a filter expression to the Find procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4aa715b7d387684d3c715836b44537020b674b81
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Question_Service_Access := Bean.Module.Get_Question_Manager; begin Manager.Save_Question (Bean); end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Question (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Question (Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then null; elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; end AWA.Questions.Beans;
Implement the answer bean
Implement the answer bean
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
66840791f5d6c690a620ba8bacad33c8ff7506e2
awa/regtests/awa-events-tests.adb
awa/regtests/awa-events-tests.adb
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with EL.Contexts.Default; with AWA.Applications; with AWA.Tests; with ADO.Sessions; package body AWA.Events.Tests is package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); end Add_Tests; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Session : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Manager.Initialize (Session); T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is App : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Session : ADO.Sessions.Master_Session := App.Get_Master_Session; Action : EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Pos : Event_Index := Find_Event_Index ("event-test-4"); begin Manager.Initialize (Session); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => "", Action => Action, Params => Props); Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Pos).Queues.Length), "Add_Action failed"); end loop; end Test_Add_Action; end AWA.Events.Tests;
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with EL.Beans; with EL.Expressions; with EL.Contexts.Default; with AWA.Applications; with AWA.Tests; with ADO.Sessions; with AWA.Events.Queues; with AWA.Events.Queues.Fifos; with AWA.Events.Services; package body AWA.Events.Tests is use AWA.Events.Services; package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4"); package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1"); package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3"); package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2"); package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5"); package Caller is new Util.Test_Caller (Test, "Events.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index", Test_Find_Event'Access); Caller.Add_Test (Suite, "Test AWA.Events.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test AWA.Events.Add_Action", Test_Add_Action'Access); end Add_Tests; -- ------------------------------ -- Test searching an event name in the definition list. -- ------------------------------ procedure Test_Find_Event (T : in out Test) is begin Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind), Integer (Find_Event_Index ("event-test-4")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind), Integer (Find_Event_Index ("event-test-5")), "Find_Event"); Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind), Integer (Find_Event_Index ("event-test-1")), "Find_Event"); end Test_Find_Event; -- ------------------------------ -- Test creation and initialization of event manager. -- ------------------------------ procedure Test_Initialize (T : in out Test) is App : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Session : ADO.Sessions.Master_Session := App.Get_Master_Session; begin Manager.Initialize (Session); -- T.Assert (Manager.Actions /= null, "Initialization failed"); end Test_Initialize; -- ------------------------------ -- Test adding an action. -- ------------------------------ procedure Test_Add_Action (T : in out Test) is use AWA.Events.Queues; App : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Manager : Event_Manager; Ctx : EL.Contexts.Default.Default_Context; Session : ADO.Sessions.Master_Session := App.Get_Master_Session; Action : EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx); Props : EL.Beans.Param_Vectors.Vector; Pos : Event_Index := Find_Event_Index ("event-test-4"); Queue : Queue_Access; begin Manager.Initialize (Session); Queue := AWA.Events.Queues.Fifos.Create_Queue ("fifo", Props, Ctx); Manager.Add_Queue (Queue); for I in 1 .. 10 loop Manager.Add_Action (Event => "event-test-4", Queue => Queue, Action => Action, Params => Props); -- Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Pos).Queues.Length), -- "Add_Action failed"); end loop; end Test_Add_Action; end AWA.Events.Tests;
Update the events unit tests
Update the events unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f3538fd600fd01e612c4ef0fcfa10181d8eff30e
src/sys/os-windows/util-streams-raw.ads
src/sys/os-windows/util-streams-raw.ads
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Systems.Os; -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>ReadFile</b> and <b>WriteFile</b>. package Util.Streams.Raw is subtype File_Type is Util.Systems.Os.File_Type; -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in File_Type); -- Get the file descriptor associated with the stream. function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type; -- Set the file descriptor to be used by the stream. procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Reposition the read/write file offset. procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode); private use Ada.Streams; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Systems.Os; with Util.Systems.Types; -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>ReadFile</b> and <b>WriteFile</b>. package Util.Streams.Raw is subtype File_Type is Util.Systems.Os.File_Type; -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in File_Type); -- Get the file descriptor associated with the stream. function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type; -- Set the file descriptor to be used by the stream. procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Reposition the read/write file offset. procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode); private use Ada.Streams; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
Fix compilation for Windows
Fix compilation for Windows
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0ea1ebe427176d4bafe9b40ee60924811b89c5f2
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; end Util.Processes.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6ed5dfc7597681fb4cde789a8fd76f593f54c76d
src/asf-server-web.adb
src/asf-server-web.adb
----------------------------------------------------------------------- -- asf.server -- ASF Server for AWS -- 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 AWS.Templates; with AWS.MIME; with AWS.Messages; with AWS.Services.Web_Block.Registry; with Ada.Strings.Fixed; with Ada.Exceptions; with EL.Beans; with ASF.Beans; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Ada.Containers.Vectors; package body ASF.Server.Web is use Util.Log; use ASF.Contexts; use Ada.Exceptions; use AWS.Templates; use ASF.Beans; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("ASF.Server.Web"); -- The logger function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data; -- Binding to record the ASF applications and bind them to URI prefixes. type Binding is record Application : Main.Application_Access; Base_URI : access String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- Register the application to serve requests procedure Register_Application (URI : in String; App : in Main.Application_Access) is Apps : constant Binding_Array_Access := new Binding_Array (1 .. Nb_Bindings + 1); begin if Applications /= null then Apps (1 .. Nb_Bindings) := Applications (1 .. Nb_Bindings); end if; Nb_Bindings := Nb_Bindings + 1; Apps (Apps'Last).Application := App; Apps (Apps'Last).Base_URI := new String '(URI); Applications := Apps; end Register_Application; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data is use ASF; use ASF.Contexts.Faces; use ASF.Applications.Views; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; begin Root_Resolver.Application := App; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Context.Set_Request (Request'Unrestricted_Access); Set_Current (Context'Unchecked_Access); Handler.Restore_View (Page, Context, View); Handler.Render_View (Context, View); Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin Bean.Free (Bean.Bean); end; Bean_Vectors.Next (C); end loop; end; return AWS.Response.Build (Content_Type => Writer.Get_Content_Type, UString_Message => Writer.Get_Response); end Dispatch; ---------------------- -- Main server callback ---------------------- function Server_Callback (Request : in AWS.Status.Data) return AWS.Response.Data is use Ada.Strings.Fixed; URI : constant String := AWS.Status.URI (Request); Slash_Pos : constant Natural := Index (URI, "/", URI'First + 1); Prefix_End : Natural; begin -- Find the module and action to invoke if Slash_Pos > 1 then Prefix_End := Slash_Pos - 1; else Prefix_End := URI'Last; end if; declare Prefix : constant String := URI (URI'First .. Prefix_End); Page : constant String := URI (Prefix_End + 1 .. URI'Last); begin for I in Applications.all'Range loop if Applications (I).Base_URI.all = Prefix then return Dispatch (Applications (I).Application, Page, Request); end if; end loop; end; return AWS.Response.Build ("text/html", "<p>Unknown application</p>"); exception when E : others => return Reply_Page_500 (Request, E); end Server_Callback; -- Return a 500 error function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data is use type AWS.Messages.Status_Code; use AWS.Services; use AWS; Translations : Templates.Translate_Set; URI : constant String := AWS.Status.URI (Request); Name : constant String := Exception_Name (E); Message : constant String := Exception_Message (E); ContentType : constant String := Web_Block.Registry.Content_Type (URI); begin Templates.Insert (Translations, Templates.Assoc ("URI", URI)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_NAME", Name)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_MESSAGE", Message)); Log.Error ("Default_Callback exception for URI '{0}': {1}: {2}", URI, Name, Message); if ContentType = AWS.MIME.Text_HTML then return AWS.Response.Build (Content_Type => AWS.MIME.Text_HTML, Message_Body => String'(Templates.Parse ("errors/exception.thtml", Translations))); else return AWS.Response.Build (Content_Type => AWS.MIME.Text_XML, Message_Body => String'(Templates.Parse ("errors/exception.txml", Translations))); end if; end Reply_Page_500; end ASF.Server.Web;
----------------------------------------------------------------------- -- asf.server -- ASF Server for AWS -- 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 AWS.Templates; with AWS.MIME; with AWS.Messages; with AWS.Services.Web_Block.Registry; with Ada.Strings.Fixed; with Ada.Exceptions; with EL.Beans; with ASF.Beans; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Ada.Containers.Vectors; package body ASF.Server.Web is use Util.Log; use ASF.Contexts; use Ada.Exceptions; use AWS.Templates; use ASF.Beans; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("ASF.Server.Web"); -- The logger function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data; -- Binding to record the ASF applications and bind them to URI prefixes. type Binding is record Application : Main.Application_Access; Base_URI : access String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then raise No_Variable with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- Register the application to serve requests procedure Register_Application (URI : in String; App : in Main.Application_Access) is Apps : constant Binding_Array_Access := new Binding_Array (1 .. Nb_Bindings + 1); begin if Applications /= null then Apps (1 .. Nb_Bindings) := Applications (1 .. Nb_Bindings); end if; Nb_Bindings := Nb_Bindings + 1; Apps (Apps'Last).Application := App; Apps (Apps'Last).Base_URI := new String '(URI); Applications := Apps; end Register_Application; function Dispatch (App : Main.Application_Access; Page : String; Request : in AWS.Status.Data) return AWS.Response.Data is use ASF; use ASF.Contexts.Faces; use ASF.Applications.Views; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; begin Root_Resolver.Application := App; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Context.Set_Request (Request'Unrestricted_Access); Set_Current (Context'Unchecked_Access); Handler.Restore_View (Page, Context, View); Handler.Render_View (Context, View); Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; return AWS.Response.Build (Content_Type => Writer.Get_Content_Type, UString_Message => Writer.Get_Response); end Dispatch; ---------------------- -- Main server callback ---------------------- function Server_Callback (Request : in AWS.Status.Data) return AWS.Response.Data is use Ada.Strings.Fixed; URI : constant String := AWS.Status.URI (Request); Slash_Pos : constant Natural := Index (URI, "/", URI'First + 1); Prefix_End : Natural; begin -- Find the module and action to invoke if Slash_Pos > 1 then Prefix_End := Slash_Pos - 1; else Prefix_End := URI'Last; end if; declare Prefix : constant String := URI (URI'First .. Prefix_End); Page : constant String := URI (Prefix_End + 1 .. URI'Last); begin for I in Applications.all'Range loop if Applications (I).Base_URI.all = Prefix then return Dispatch (Applications (I).Application, Page, Request); end if; end loop; end; return AWS.Response.Build ("text/html", "<p>Unknown application</p>"); exception when E : others => return Reply_Page_500 (Request, E); end Server_Callback; -- Return a 500 error function Reply_Page_500 (Request : in AWS.Status.Data; E : in Exception_Occurrence) return AWS.Response.Data is use type AWS.Messages.Status_Code; use AWS.Services; use AWS; Translations : Templates.Translate_Set; URI : constant String := AWS.Status.URI (Request); Name : constant String := Exception_Name (E); Message : constant String := Exception_Message (E); ContentType : constant String := Web_Block.Registry.Content_Type (URI); begin Templates.Insert (Translations, Templates.Assoc ("URI", URI)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_NAME", Name)); Templates.Insert (Translations, Templates.Assoc ("EXCEPTION_MESSAGE", Message)); Log.Error ("Default_Callback exception for URI '{0}': {1}: {2}", URI, Name, Message); if ContentType = AWS.MIME.Text_HTML then return AWS.Response.Build (Content_Type => AWS.MIME.Text_HTML, Message_Body => String'(Templates.Parse ("errors/exception.thtml", Translations))); else return AWS.Response.Build (Content_Type => AWS.MIME.Text_XML, Message_Body => String'(Templates.Parse ("errors/exception.txml", Translations))); end if; end Reply_Page_500; end ASF.Server.Web;
Raise an exception if we cannot create a bean
Raise an exception if we cannot create a bean
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
b864a1adb869b271c56eef415a73aa86cb57badf
src/util-commands-parsers-gnat_parser.ads
src/util-commands-parsers-gnat_parser.ads
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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; package Util.Commands.Parsers.GNAT_Parser is subtype Config_Type is GNAT.Command_Line.Command_Line_Configuration; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)); package Config_Parser is new Util.Commands.Parsers.Config_Parser (Config_Type => Config_Type, Execute => Execute); end Util.Commands.Parsers.GNAT_Parser;
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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; package Util.Commands.Parsers.GNAT_Parser is subtype Config_Type is GNAT.Command_Line.Command_Line_Configuration; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)); procedure Usage (Name : in String; Config : in out Config_Type); package Config_Parser is new Util.Commands.Parsers.Config_Parser (Config_Type => Config_Type, Execute => Execute); end Util.Commands.Parsers.GNAT_Parser;
Declare the Usage procedure
Declare the Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ed6579c48ed275e21fbc3bf42235bd05d516790c
awa/samples/src/atlas-applications.ads
awa/samples/src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Servlets.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; -- XXX_Module : aliased Atlas.XXX.Module.XXX_Module; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 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.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Servlets.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) function Get_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; -- XXX_Module : aliased Atlas.XXX.Module.XXX_Module; end record; end Atlas.Applications;
Add the comments module
Add the comments module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b45a65683b3f26bfd68e8b1f02cc0e2129ded079
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Declare the Create_Invitation_Bean function
Declare the Create_Invitation_Bean function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
34af5c5ab0ae73e572164a8ab3444b93cf529126
src/security-filters.ads
src/security-filters.ads
----------------------------------------------------------------------- -- security-filters -- Security filter -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Filters; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Sessions; with ASF.Principals; with Security.Permissions; -- The <b>Security.Filters</b> package defines a servlet filter that can be activated -- on requests to authenticate users and verify they have the permission to view -- a page. package Security.Filters is SID_COOKIE : constant String := "SID"; AID_COOKIE : constant String := "AID"; type Auth_Filter is new ASF.Filters.Filter with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. procedure Initialize (Server : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Set the permission manager that must be used to verify the permission. procedure Set_Permission_Manager (Filter : in out Auth_Filter; Manager : in Security.Permissions.Permission_Manager_Access); -- Filter the request to make sure the user is authenticated. -- Invokes the <b>Do_Login</b> procedure if there is no user. -- If a permission manager is defined, check that the user has the permission -- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission -- is denied. procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. procedure Do_Login (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Display the forbidden access page. This procedure is called when the user is not -- authorized to see the page. The default implementation returns the SC_FORBIDDEN error. procedure Do_Deny (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- 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. 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); private type Auth_Filter is new ASF.Filters.Filter with record Manager : Security.Permissions.Permission_Manager_Access := null; end record; end Security.Filters;
----------------------------------------------------------------------- -- security-filters -- Security filter -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Filters; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Sessions; with ASF.Principals; with Security.Permissions; -- The <b>Security.Filters</b> package defines a servlet filter that can be activated -- on requests to authenticate users and verify they have the permission to view -- a page. package Security.Filters is SID_COOKIE : constant String := "SID"; AID_COOKIE : constant String := "AID"; type Auth_Filter is new ASF.Filters.Filter with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Set the permission manager that must be used to verify the permission. procedure Set_Permission_Manager (Filter : in out Auth_Filter; Manager : in Security.Permissions.Permission_Manager_Access); -- Filter the request to make sure the user is authenticated. -- Invokes the <b>Do_Login</b> procedure if there is no user. -- If a permission manager is defined, check that the user has the permission -- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission -- is denied. procedure Do_Filter (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. procedure Do_Login (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Display the forbidden access page. This procedure is called when the user is not -- authorized to see the page. The default implementation returns the SC_FORBIDDEN error. procedure Do_Deny (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- 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. 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); private type Auth_Filter is new ASF.Filters.Filter with record Manager : Security.Permissions.Permission_Manager_Access := null; end record; end Security.Filters;
Mark initialize as overriding
Mark initialize as overriding
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
627bb51268a834c206c35c0b1b788404e88780dd
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_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; 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); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; 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); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; private end MAT.Memory;
Add the Min_Addr and Max_Addr to report the memory region allocated for the thread
Add the Min_Addr and Max_Addr to report the memory region allocated for the thread
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
bcae103643daf8f1304995e48a92da1982f53ac4
src/orka/implementation/orka-resources-locations-directories.adb
src/orka/implementation/orka-resources-locations-directories.adb
-- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Directories; package body Orka.Resources.Locations.Directories is use Ada.Streams; function Open_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Open (Result.File, Stream_IO.In_File, File_Name); end return; end Open_File; overriding procedure Finalize (Object : in out Byte_Array_File) is begin if not Object.Finalized then if Stream_IO.Is_Open (Object.File) then Stream_IO.Close (Object.File); end if; Object.Finalized := True; end if; end Finalize; function Read_File (Object : in out Byte_Array_File) return Byte_Array_Access is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Integer (Stream_IO.Size (Object.File)); subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); Raw_Contents : Byte_Array_Access := new File_Byte_Array; begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Read (File_Stream, Raw_Contents.all); return Raw_Contents; exception when others => Free_Byte_Array (Raw_Contents); raise; end Read_File; ----------------------------------------------------------------------------- function Create_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Create (Result.File, Stream_IO.Out_File, File_Name); end return; end Create_File; procedure Write_Data (Object : in out Byte_Array_File; Data : Byte_Array_Access) is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Data'Length; subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Write (File_Stream, Data.all); end Write_Data; ----------------------------------------------------------------------------- overriding function Exists (Object : Directory_Location; Path : String) return Boolean is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; begin return Ada.Directories.Exists (Full_Path); end Exists; overriding function Read_Data (Object : Directory_Location; Path : String) return not null Byte_Array_Access is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if not Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Ordinary_File then raise Name_Error with "Path '" & Full_Path & "' is not a regular file"; end if; declare File : constant Byte_Array_File'Class := Open_File (Full_Path); begin return File.Read_File; end; end Read_Data; overriding procedure Write_Data (Object : Writable_Directory_Location; Path : String; Data : Byte_Array_Access) is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' already exists"; end if; declare File : constant Byte_Array_File'Class := Create_File (Full_Path); begin File.Write_Data (Data); end; end Write_Data; function Create_Location (Path : String) return Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; return new Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)); end Create_Location; function Create_Location (Path : String) return Writable_Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; -- The pointer is stored in a variable to make the compiler happy return Result : constant Writable_Location_Ptr := new Writable_Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)) do null; end return; end Create_Location; end Orka.Resources.Locations.Directories;
-- Copyright (c) 2018 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Directories; package body Orka.Resources.Locations.Directories is use Ada.Streams; function Open_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Open (Result.File, Stream_IO.In_File, File_Name); end return; end Open_File; overriding procedure Finalize (Object : in out Byte_Array_File) is begin if not Object.Finalized then if Stream_IO.Is_Open (Object.File) then Stream_IO.Close (Object.File); end if; Object.Finalized := True; end if; end Finalize; function Read_File (Object : Byte_Array_File) return Byte_Array_Access is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Integer (Stream_IO.Size (Object.File)); subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); Raw_Contents : Byte_Array_Access := new File_Byte_Array; begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Read (File_Stream, Raw_Contents.all); return Raw_Contents; exception when others => Free_Byte_Array (Raw_Contents); raise; end Read_File; ----------------------------------------------------------------------------- function Create_File (File_Name : String) return Byte_Array_File is begin return Result : Byte_Array_File := (Ada.Finalization.Limited_Controlled with File => <>, Finalized => False) do Stream_IO.Create (Result.File, Stream_IO.Out_File, File_Name); end return; end Create_File; procedure Write_Data (Object : Byte_Array_File; Data : Byte_Array_Access) is File_Stream : Stream_IO.Stream_Access; File_Size : constant Integer := Data'Length; subtype File_Byte_Array is Byte_Array (1 .. Stream_Element_Offset (File_Size)); begin File_Stream := Stream_IO.Stream (Object.File); File_Byte_Array'Write (File_Stream, Data.all); end Write_Data; ----------------------------------------------------------------------------- overriding function Exists (Object : Directory_Location; Path : String) return Boolean is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; begin return Ada.Directories.Exists (Full_Path); end Exists; overriding function Read_Data (Object : Directory_Location; Path : String) return not null Byte_Array_Access is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if not Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Ordinary_File then raise Name_Error with "Path '" & Full_Path & "' is not a regular file"; end if; declare File : constant Byte_Array_File := Open_File (Full_Path); begin return File.Read_File; end; end Read_Data; overriding procedure Write_Data (Object : Writable_Directory_Location; Path : String; Data : Byte_Array_Access) is Directory : String renames SU.To_String (Object.Full_Path); Full_Path : constant String := Directory & Path_Separator & Path; use Ada.Directories; begin if Exists (Full_Path) then raise Name_Error with "File '" & Full_Path & "' already exists"; end if; declare File : constant Byte_Array_File := Create_File (Full_Path); begin File.Write_Data (Data); end; end Write_Data; function Create_Location (Path : String) return Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; return new Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)); end Create_Location; function Create_Location (Path : String) return Writable_Location_Ptr is use Ada.Directories; Full_Path : constant String := Full_Name (Path); begin if not Exists (Full_Path) then raise Name_Error with "Directory '" & Full_Path & "' not found"; end if; if Kind (Full_Path) /= Directory then raise Name_Error with "Path '" & Full_Path & "' is not a directory"; end if; -- The pointer is stored in a variable to make the compiler happy return Result : constant Writable_Location_Ptr := new Writable_Directory_Location'(Full_Path => SU.To_Unbounded_String (Full_Path)) do null; end return; end Create_Location; end Orka.Resources.Locations.Directories;
Fix compile errors with GCC 8
Fix compile errors with GCC 8 Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f063aa9e36019d9daf7d9548c51751718cb626c9
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Documents.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Definition : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Definition (Document, Definition); else Wiki.Documents.Add_Definition (Document, Definition); end if; end Add_Definition; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List (Document, Level, Ordered); else Document.Add_List (Level, Ordered); end if; end Add_List; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Add_Row (Document); else Document.Add_Row; end if; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Column (Document, Attributes); else Document.Add_Column (Attributes); end if; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish_Table (Document); else Document.Finish_Table; end if; end Finish_Table; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin -- if Filter.Next /= null then -- Filter.Next.Add_Header (Document, Header, Level); -- else -- Wiki.Documents.Append (Document, Header, Level); -- end if; null; end Add_Header; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Definition : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Definition (Document, Definition); else Wiki.Documents.Add_Definition (Document, Definition); end if; end Add_Definition; procedure Start_Block (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Node_Kind; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Start_Block (Document, Kind, Level); else Document.Start_Block (Kind, Level); end if; end Start_Block; procedure End_Block (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Node_Kind) is begin if Filter.Next /= null then Filter.Next.End_Block (Document, Kind); else Document.End_Block (Kind); end if; end End_Block; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List (Document, Level, Ordered); else Document.Add_List (Level, Ordered); end if; end Add_List; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add a link reference with the given label. -- ------------------------------ procedure Add_Link_Ref (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Label : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Link_Ref (Document, Label); else Document.Add_Link_Ref (Label); end if; end Add_Link_Ref; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Add_Row (Document); else Document.Add_Row; end if; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Column (Document, Attributes); else Document.Add_Column (Attributes); end if; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish_Table (Document); else Document.Finish_Table; end if; end Finish_Table; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
Add Start_Block, End_Block, Add_Link_Ref
Add Start_Block, End_Block, Add_Link_Ref
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2c978d60246b353a73e0e338f3002ad4a2005320
matp/src/frames/mat-frames-print.adb
matp/src/frames/mat-frames-print.adb
----------------------------------------------------------------------- -- 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.Text_IO; use Ada.Text_IO; with MAT.Types; with System.Address_Image; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth - F.Local_Depth + 1; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; 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; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin Set_Col (File, Positive_Count (Depth)); if F.Parent = null then Put_Line (File, "R " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address)); else Put_Line (File, "F " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address) & " - P=" & System.Address_Image (F.Parent.all'Address)); end if; for I in 1 .. F.Local_Depth loop Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Calls (I)); Put_Line (File, " D " & Natural'Image (Depth)); Depth := Depth + 1; end loop; Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
----------------------------------------------------------------------- -- 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.Text_IO; use Ada.Text_IO; with MAT.Types; with System.Address_Image; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : Natural := F.Depth; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; 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; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin Set_Col (File, Positive_Count (Depth)); if F.Parent = null then Put_Line (File, "R " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address)); else Put_Line (File, "F " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address) & " - P=" & System.Address_Image (F.Parent.all'Address)); end if; Set_Col (File, Positive_Count (Depth)); Print_Address (File, F.Pc); Put_Line (File, " D " & Natural'Image (Depth)); Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
Update the Print of stack frame
Update the Print of stack frame
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1b4f4c1e0fa49ed32f225ce5961c194fb50172cd
src/sys/encoders/util-encoders-base64.adb
src/sys/encoders/util-encoders-base64.adb
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in base64adecimal -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; package body Util.Encoders.Base64 is use Interfaces; use Ada; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encode the 64-bit value to LEB128 and then base64url. -- ------------------------------ function Encode (Value : in Interfaces.Unsigned_64) return String is E : Encoder; Data : Ada.Streams.Stream_Element_Array (1 .. 10); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : String (1 .. 16); Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length); for Buf'Address use Result'Address; pragma Import (Ada, Buf); begin -- Encode the integer to LEB128 in the data buffer. Encode_LEB128 (Into => Data, Pos => Data'First, Val => Value, Last => Last); -- Encode the data buffer in base64url. E.Set_URL_Mode (True); E.Transform (Data => Data (Data'First .. Last), Into => Buf, Last => Last, Encoded => Encoded); E.Finish (Into => Buf (Last + 1 .. Buf'Last), Last => Last); -- Strip the '=' or '==' at end of base64url. if Result (Positive (Last)) /= '=' then return Result (Result'First .. Positive (Last)); elsif Result (Positive (Last) - 1) /= '=' then return Result (Result'First .. Positive (Last) - 1); else return Result (Result'First .. Positive (Last) - 2); end if; end Encode; -- ------------------------------ -- Decode the base64url string and then the LEB128 integer. -- Raise the Encoding_Error if the string is invalid and cannot be decoded. -- ------------------------------ function Decode (Value : in String) return Interfaces.Unsigned_64 is D : Decoder; Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : Interfaces.Unsigned_64; End_Pos : constant Ada.Streams.Stream_Element_Offset := Value'Length + ((4 - (Value'Length mod 4)) mod 4); begin if Buf'Length < End_Pos then raise Encoding_Error with "Input string is too short"; end if; Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value); -- Set back the '=' for the base64url (pad to multiple of 4. Buf (Value'Length + 1) := Character'Pos ('='); Buf (Value'Length + 2) := Character'Pos ('='); -- Decode using base64url D.Set_URL_Mode (True); D.Transform (Data => Buf (Buf'First .. End_Pos), Into => R, Last => Last, Encoded => Encoded); if Encoded /= End_Pos then raise Encoding_Error with "Input string is too short"; end if; -- Decode the LEB128 number. Decode_LEB128 (From => R (R'First .. Last), Pos => R'First, Val => Result, Last => Encoded); -- Check that everything was decoded. if Last + 1 /= Encoded then raise Encoding_Error with "Input string contains garbage at the end"; end if; return Result; end Decode; -- ------------------------------ -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Unsigned_8; Alphabet : constant Alphabet_Access := E.Alphabet; begin while E.Count /= 0 and I <= Data'Last loop if E.Count = 2 then C1 := E.Value; C2 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); Pos := Pos + 1; I := I + 1; E.Count := 1; E.Value := C2; else C2 := E.Value; C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 1) := Alphabet (C1 and 16#03F#); Pos := Pos + 2; I := I + 1; E.Count := 0; end if; end loop; while I <= Data'Last loop if Pos + 4 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; E.Count := 0; return; end if; -- Encode the first byte, add padding if necessary. C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Right (C1, 2)); if I = Data'Last then E.Value := C1; E.Count := 2; Last := Pos; Encoded := Data'Last; return; end if; -- Encode the second byte, add padding if necessary. C2 := Unsigned_8 (Data (I + 1)); Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); if I = Data'Last - 1 then E.Value := C2; E.Count := 1; Last := Pos + 1; Encoded := Data'Last; return; end if; -- Encode the third byte C1 := Unsigned_8 (Data (I + 2)); Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 3) := Alphabet (C1 and 16#03F#); Pos := Pos + 4; I := I + 3; end loop; E.Count := 0; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Finish encoding the input array. -- ------------------------------ overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Pos : constant Ada.Streams.Stream_Element_Offset := Into'First; begin if E.Count = 2 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 3, 4)); Into (Pos + 1) := Character'Pos ('='); Into (Pos + 2) := Character'Pos ('='); Last := Pos + 2; E.Count := 0; elsif E.Count = 1 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 16#0F#, 2)); Into (Pos + 1) := Character'Pos ('='); Last := Pos + 1; E.Count := 0; else Last := Pos - 1; end if; end Finish; -- ------------------------------ -- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Encoder; Mode : in Boolean) is begin if Mode then E.Alphabet := BASE64_URL_ALPHABET'Access; else E.Alphabet := BASE64_ALPHABET'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 encoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Encoder return Transformer_Access is begin return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access, others => <>); end Create_URL_Encoder; -- ------------------------------ -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary 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 Decoder; 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 use Ada.Streams; Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Ada.Streams.Stream_Element; Val1, Val2 : Unsigned_8; Values : constant Alphabet_Values_Access := E.Values; begin while I <= Data'Last loop if Pos + 3 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; return; end if; -- Decode the first two bytes to produce the first output byte C1 := Data (I); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; C2 := Data (I + 1); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4)); if I + 2 > Data'Last then Encoded := I + 1; Last := Pos; return; end if; -- Decode the next byte C1 := Data (I + 2); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then if C1 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; Encoded := I + 3; Last := Pos; return; end if; Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2)); if I + 3 > Data'Last then Encoded := I + 2; Last := Pos + 1; return; end if; C2 := Data (I + 3); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then if C2 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Encoded := I + 3; Last := Pos + 1; return; end if; Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2); Pos := Pos + 3; I := I + 4; end loop; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Decoder; Mode : in Boolean) is begin if Mode then E.Values := BASE64_URL_VALUES'Access; else E.Values := BASE64_VALUES'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 decoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Decoder return Transformer_Access is begin return new Decoder '(Values => BASE64_URL_VALUES'Access); end Create_URL_Decoder; end Util.Encoders.Base64;
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in base64 -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 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.Streams; package body Util.Encoders.Base64 is use Interfaces; -- ------------------------------ -- Encode the 64-bit value to LEB128 and then base64url. -- ------------------------------ function Encode (Value : in Interfaces.Unsigned_64) return String is E : Encoder; Data : Ada.Streams.Stream_Element_Array (1 .. 10); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : String (1 .. 16); Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length); for Buf'Address use Result'Address; pragma Import (Ada, Buf); begin -- Encode the integer to LEB128 in the data buffer. Encode_LEB128 (Into => Data, Pos => Data'First, Val => Value, Last => Last); -- Encode the data buffer in base64url. E.Set_URL_Mode (True); E.Transform (Data => Data (Data'First .. Last), Into => Buf, Last => Last, Encoded => Encoded); E.Finish (Into => Buf (Last + 1 .. Buf'Last), Last => Last); -- Strip the '=' or '==' at end of base64url. if Result (Positive (Last)) /= '=' then return Result (Result'First .. Positive (Last)); elsif Result (Positive (Last) - 1) /= '=' then return Result (Result'First .. Positive (Last) - 1); else return Result (Result'First .. Positive (Last) - 2); end if; end Encode; -- ------------------------------ -- Decode the base64url string and then the LEB128 integer. -- Raise the Encoding_Error if the string is invalid and cannot be decoded. -- ------------------------------ function Decode (Value : in String) return Interfaces.Unsigned_64 is D : Decoder; Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : Interfaces.Unsigned_64; End_Pos : constant Ada.Streams.Stream_Element_Offset := Value'Length + ((4 - (Value'Length mod 4)) mod 4); begin if Buf'Length < End_Pos then raise Encoding_Error with "Input string is too short"; end if; Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value); -- Set back the '=' for the base64url (pad to multiple of 4. Buf (Value'Length + 1) := Character'Pos ('='); Buf (Value'Length + 2) := Character'Pos ('='); -- Decode using base64url D.Set_URL_Mode (True); D.Transform (Data => Buf (Buf'First .. End_Pos), Into => R, Last => Last, Encoded => Encoded); if Encoded /= End_Pos then raise Encoding_Error with "Input string is too short"; end if; -- Decode the LEB128 number. Decode_LEB128 (From => R (R'First .. Last), Pos => R'First, Val => Result, Last => Encoded); -- Check that everything was decoded. if Last + 1 /= Encoded then raise Encoding_Error with "Input string contains garbage at the end"; end if; return Result; end Decode; -- ------------------------------ -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. -- ------------------------------ overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Unsigned_8; Alphabet : constant Alphabet_Access := E.Alphabet; begin while E.Count /= 0 and I <= Data'Last loop if E.Count = 2 then C1 := E.Value; C2 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); Pos := Pos + 1; I := I + 1; E.Count := 1; E.Value := C2; else C2 := E.Value; C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 1) := Alphabet (C1 and 16#03F#); Pos := Pos + 2; I := I + 1; E.Count := 0; end if; end loop; while I <= Data'Last loop if Pos + 4 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; E.Count := 0; return; end if; -- Encode the first byte, add padding if necessary. C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Right (C1, 2)); if I = Data'Last then E.Value := C1; E.Count := 2; Last := Pos; Encoded := Data'Last; return; end if; -- Encode the second byte, add padding if necessary. C2 := Unsigned_8 (Data (I + 1)); Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); if I = Data'Last - 1 then E.Value := C2; E.Count := 1; Last := Pos + 1; Encoded := Data'Last; return; end if; -- Encode the third byte C1 := Unsigned_8 (Data (I + 2)); Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 3) := Alphabet (C1 and 16#03F#); Pos := Pos + 4; I := I + 3; end loop; E.Count := 0; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Finish encoding the input array. -- ------------------------------ overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is Pos : constant Ada.Streams.Stream_Element_Offset := Into'First; begin if E.Count = 2 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 3, 4)); Into (Pos + 1) := Character'Pos ('='); Into (Pos + 2) := Character'Pos ('='); Last := Pos + 2; E.Count := 0; elsif E.Count = 1 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 16#0F#, 2)); Into (Pos + 1) := Character'Pos ('='); Last := Pos + 1; E.Count := 0; else Last := Pos - 1; end if; end Finish; -- ------------------------------ -- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Encoder; Mode : in Boolean) is begin if Mode then E.Alphabet := BASE64_URL_ALPHABET'Access; else E.Alphabet := BASE64_ALPHABET'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 encoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Encoder return Transformer_Access is begin return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access, others => <>); end Create_URL_Encoder; -- ------------------------------ -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary 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 Decoder; 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 Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Ada.Streams.Stream_Element; Val1, Val2 : Unsigned_8; Values : constant Alphabet_Values_Access := E.Values; begin while I <= Data'Last loop if Pos + 3 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; return; end if; -- Decode the first two bytes to produce the first output byte C1 := Data (I); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; C2 := Data (I + 1); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4)); if I + 2 > Data'Last then Encoded := I + 1; Last := Pos; return; end if; -- Decode the next byte C1 := Data (I + 2); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then if C1 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; Encoded := I + 3; Last := Pos; return; end if; Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2)); if I + 3 > Data'Last then Encoded := I + 2; Last := Pos + 1; return; end if; C2 := Data (I + 3); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then if C2 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Encoded := I + 3; Last := Pos + 1; return; end if; Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2); Pos := Pos + 3; I := I + 4; end loop; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Decoder; Mode : in Boolean) is begin if Mode then E.Values := BASE64_URL_VALUES'Access; else E.Values := BASE64_VALUES'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 decoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Decoder return Transformer_Access is begin return new Decoder '(Values => BASE64_URL_VALUES'Access); end Create_URL_Decoder; end Util.Encoders.Base64;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ff95e5c684498f5308f20478d92695878aa51107
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is pragma Unreferenced (T); begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); Application.Start; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access); end Initialize_Filters; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is pragma Unreferenced (T); begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Application.Close; Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); Application.Start; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); -- App.Add_Servlet (Name => "auth", Server => App.Auth'Unchecked_Access); -- App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access); end Initialize_Filters; end AWA.Tests;
Call the application Close procedure when tests are finished
Call the application Close procedure when tests are finished
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b7e5ba0b14be3dc32e0f6d9ce9d9b1ef27d8f56b
src/gl/implementation/gl-enums-getter.ads
src/gl/implementation/gl-enums-getter.ads
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package GL.Enums.Getter is pragma Preelaborate; type Parameter is (Point_Size, Point_Size_Range, Point_Size_Granularity, Line_Smooth, Line_Width, Smooth_Line_Width_Range, Smooth_Line_Width_Granularity, Polygon_Mode, Polygon_Smooth, Edge_Flag, Cull_Face, Cull_Face_Mode, Front_Face, Shade_Model, Depth_Range, Depth_Test, Depth_Writemask, Depth_Clear_Value, Depth_Func, Stencil_Test, Stencil_Clear_Value, Stencil_Func, Stencil_Value_Mask, Stencil_Fail, Stencil_Pass_Depth_Fail, Stencil_Pass_Depth_Pass, Stencil_Ref, Stencil_Writemask, Viewport, Dither, Blend_Dst, Blend_Src, Blend, Logic_Op_Mode, Index_Logic_Op, Color_Logic_Op, Aux_Buffers, Draw_Buffer, Read_Buffer, Scissor_Box, Scissor_Test, Color_Clear_Value, Color_Writemask, Index_Mode, Rgba_Mode, Doublebuffer, Stereo, Render_Mode, Line_Smooth_Hint, Polygon_Smooth_Hint, Unpack_Swap_Bytes, Unpack_Lsb_First, Unpack_Row_Length, Unpack_Skip_Rows, Unpack_Skip_Pixels, Unpack_Alignment, Pack_Swap_Bytes, Pack_Lsb_First, Pack_Row_Length, Pack_Skip_Rows, Pack_Skip_Pixels, Pack_Alignment, Max_Clip_Distances, Max_Texture_Size, Max_Pixel_Map_Table, Max_Viewport_Dims, Subpixel_Bits, Texture_1D, Texture_2D, Feedback_Buffer_Pointer, Feedback_Buffer_Size, Feedback_Buffer_Type, Selection_Buffer_Pointer, Selection_Buffer_Size, Blend_Color, Blend_Equation_RGB, Pack_Skip_Images, Pack_Image_Height, Unpack_Skip_Images, Unpack_Image_Height, Blend_Dst_RGB, Blend_Src_RGB, Blend_Dst_Alpha, Blend_Src_Alpha, Major_Version, Minor_Version, Num_Extensions, Num_Shading_Language_Versions, Aliased_Line_Width_Range, Active_Texture, Max_Texture_Max_Anisotropy, Stencil_Back_Func, Stencil_Back_Fail, Stencil_Back_Pass_Depth_Fail, Stencil_Back_Pass_Depth_Pass, Blend_Equation_Alpha, Max_Combined_Texture_Image_Units, Min_Sample_Shading_Value, Stencil_Back_Ref, Stencil_Back_Value_Mask, Stencil_Back_Writemask, Timestamp, Max_Debug_Message_Length, Debug_Logged_Messages, Max_Framebuffer_Width, Max_Framebuffer_Height, Max_Framebuffer_Layers, Max_Framebuffer_Samples); type String_Parameter is (Vendor, Renderer, Version, Extensions, Shading_Language_Version); type Renderbuffer_Parameter is (Width, Height, Internal_Format, Red_Size, Green_Size, Blue_Size, Alpha_Size, Depth_Size, Stencil_Size); private for Parameter use (Point_Size => 16#0B11#, Point_Size_Range => 16#0B12#, Point_Size_Granularity => 16#0B13#, Line_Smooth => 16#0B20#, Line_Width => 16#0B21#, Smooth_Line_Width_Range => 16#0B22#, Smooth_Line_Width_Granularity => 16#0B23#, Polygon_Mode => 16#0B40#, Polygon_Smooth => 16#0B41#, Edge_Flag => 16#0B43#, Cull_Face => 16#0B44#, Cull_Face_Mode => 16#0B45#, Front_Face => 16#0B46#, Shade_Model => 16#0B54#, Depth_Range => 16#0B70#, Depth_Test => 16#0B71#, Depth_Writemask => 16#0B72#, Depth_Clear_Value => 16#0B73#, Depth_Func => 16#0B74#, Stencil_Test => 16#0B90#, Stencil_Clear_Value => 16#0B91#, Stencil_Func => 16#0B92#, Stencil_Value_Mask => 16#0B93#, Stencil_Fail => 16#0B94#, Stencil_Pass_Depth_Fail => 16#0B95#, Stencil_Pass_Depth_Pass => 16#0B96#, Stencil_Ref => 16#0B97#, Stencil_Writemask => 16#0B98#, Viewport => 16#0BA2#, Dither => 16#0BD0#, Blend_Dst => 16#0BE0#, Blend_Src => 16#0BE1#, Blend => 16#0BE2#, Logic_Op_Mode => 16#0BF0#, Index_Logic_Op => 16#0BF1#, Color_Logic_Op => 16#0BF2#, Aux_Buffers => 16#0C00#, Draw_Buffer => 16#0C01#, Read_Buffer => 16#0C02#, Scissor_Box => 16#0C10#, Scissor_Test => 16#0C11#, Color_Clear_Value => 16#0C22#, Color_Writemask => 16#0C23#, Index_Mode => 16#0C30#, Rgba_Mode => 16#0C31#, Doublebuffer => 16#0C32#, Stereo => 16#0C33#, Render_Mode => 16#0C40#, Line_Smooth_Hint => 16#0C52#, Polygon_Smooth_Hint => 16#0C53#, Unpack_Swap_Bytes => 16#0CF0#, Unpack_Lsb_First => 16#0CF1#, Unpack_Row_Length => 16#0CF2#, Unpack_Skip_Rows => 16#0CF3#, Unpack_Skip_Pixels => 16#0CF4#, Unpack_Alignment => 16#0CF5#, Pack_Swap_Bytes => 16#0D00#, Pack_Lsb_First => 16#0D01#, Pack_Row_Length => 16#0D02#, Pack_Skip_Rows => 16#0D03#, Pack_Skip_Pixels => 16#0D04#, Pack_Alignment => 16#0D05#, Max_Clip_Distances => 16#0D32#, Max_Texture_Size => 16#0D33#, Max_Pixel_Map_Table => 16#0D34#, Max_Viewport_Dims => 16#0D3A#, Subpixel_Bits => 16#0D50#, Texture_1D => 16#0DE0#, Texture_2D => 16#0DE1#, Feedback_Buffer_Pointer => 16#0DF0#, Feedback_Buffer_Size => 16#0DF1#, Feedback_Buffer_Type => 16#0DF2#, Selection_Buffer_Pointer => 16#0DF3#, Selection_Buffer_Size => 16#0DF4#, Blend_Color => 16#8005#, Blend_Equation_RGB => 16#8009#, Pack_Skip_Images => 16#806B#, Pack_Image_Height => 16#806C#, Unpack_Skip_Images => 16#806D#, Unpack_Image_Height => 16#806E#, Blend_Dst_RGB => 16#80C8#, Blend_Src_RGB => 16#80C9#, Blend_Dst_Alpha => 16#80CA#, Blend_Src_Alpha => 16#80CB#, Major_Version => 16#821B#, Minor_Version => 16#821C#, Num_Extensions => 16#821D#, Num_Shading_Language_Versions => 16#82E9#, Aliased_Line_Width_Range => 16#846E#, Active_Texture => 16#84E0#, Max_Texture_Max_Anisotropy => 16#84FF#, Stencil_Back_Func => 16#8800#, Stencil_Back_Fail => 16#8801#, Stencil_Back_Pass_Depth_Fail => 16#8802#, Stencil_Back_Pass_Depth_Pass => 16#8803#, Blend_Equation_Alpha => 16#883D#, Max_Combined_Texture_Image_Units => 16#8B4D#, Min_Sample_Shading_Value => 16#8C37#, Stencil_Back_Ref => 16#8CA3#, Stencil_Back_Value_Mask => 16#8CA4#, Stencil_Back_Writemask => 16#8CA5#, Timestamp => 16#8E28#, Max_Debug_Message_Length => 16#9143#, Debug_Logged_Messages => 16#9145#, Max_Framebuffer_Width => 16#9315#, Max_Framebuffer_Height => 16#9316#, Max_Framebuffer_Layers => 16#9317#, Max_Framebuffer_Samples => 16#9318#); for Parameter'Size use Low_Level.Enum'Size; for String_Parameter use (Vendor => 16#1F00#, Renderer => 16#1F01#, Version => 16#1F02#, Extensions => 16#1F03#, Shading_Language_Version => 16#8B8C#); for String_Parameter'Size use Low_Level.Enum'Size; for Renderbuffer_Parameter use (Width => 16#8D42#, Height => 16#8D43#, Internal_Format => 16#8D44#, Red_Size => 16#8D50#, Green_Size => 16#8D51#, Blue_Size => 16#8D52#, Alpha_Size => 16#8D53#, Depth_Size => 16#8D54#, Stencil_Size => 16#8D55#); for Renderbuffer_Parameter'Size use Low_Level.Enum'Size; end GL.Enums.Getter;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package GL.Enums.Getter is pragma Preelaborate; type Parameter is (Point_Size, Point_Size_Range, Point_Size_Granularity, Line_Smooth, Line_Width, Smooth_Line_Width_Range, Smooth_Line_Width_Granularity, Polygon_Mode, Polygon_Smooth, Cull_Face, Cull_Face_Mode, Front_Face, Depth_Range, Depth_Test, Depth_Writemask, Depth_Clear_Value, Depth_Func, Stencil_Test, Stencil_Clear_Value, Stencil_Func, Stencil_Value_Mask, Stencil_Fail, Stencil_Pass_Depth_Fail, Stencil_Pass_Depth_Pass, Stencil_Ref, Stencil_Writemask, Viewport, Dither, Blend_Dst, Blend_Src, Blend, Logic_Op_Mode, Color_Logic_Op, Draw_Buffer, Read_Buffer, Scissor_Box, Scissor_Test, Color_Clear_Value, Color_Writemask, Doublebuffer, Stereo, Line_Smooth_Hint, Polygon_Smooth_Hint, Unpack_Swap_Bytes, Unpack_Lsb_First, Unpack_Row_Length, Unpack_Skip_Rows, Unpack_Skip_Pixels, Unpack_Alignment, Pack_Swap_Bytes, Pack_Lsb_First, Pack_Row_Length, Pack_Skip_Rows, Pack_Skip_Pixels, Pack_Alignment, Max_Clip_Distances, Max_Texture_Size, Max_Viewport_Dims, Subpixel_Bits, Texture_1D, Texture_2D, Blend_Color, Blend_Equation_RGB, Pack_Skip_Images, Pack_Image_Height, Unpack_Skip_Images, Unpack_Image_Height, Blend_Dst_RGB, Blend_Src_RGB, Blend_Dst_Alpha, Blend_Src_Alpha, Major_Version, Minor_Version, Num_Extensions, Num_Shading_Language_Versions, Aliased_Line_Width_Range, Active_Texture, Max_Texture_Max_Anisotropy, -- Part of EXT_texture_filter_anisotropic Stencil_Back_Func, Stencil_Back_Fail, Stencil_Back_Pass_Depth_Fail, Stencil_Back_Pass_Depth_Pass, Blend_Equation_Alpha, Max_Combined_Texture_Image_Units, Min_Sample_Shading_Value, Stencil_Back_Ref, Stencil_Back_Value_Mask, Stencil_Back_Writemask, Timestamp, Max_Debug_Message_Length, Debug_Logged_Messages, Max_Framebuffer_Width, Max_Framebuffer_Height, Max_Framebuffer_Layers, Max_Framebuffer_Samples); type String_Parameter is (Vendor, Renderer, Version, Extensions, Shading_Language_Version); type Renderbuffer_Parameter is (Width, Height, Internal_Format, Red_Size, Green_Size, Blue_Size, Alpha_Size, Depth_Size, Stencil_Size); private for Parameter use (Point_Size => 16#0B11#, Point_Size_Range => 16#0B12#, Point_Size_Granularity => 16#0B13#, Line_Smooth => 16#0B20#, Line_Width => 16#0B21#, Smooth_Line_Width_Range => 16#0B22#, Smooth_Line_Width_Granularity => 16#0B23#, Polygon_Mode => 16#0B40#, Polygon_Smooth => 16#0B41#, Cull_Face => 16#0B44#, Cull_Face_Mode => 16#0B45#, Front_Face => 16#0B46#, Depth_Range => 16#0B70#, Depth_Test => 16#0B71#, Depth_Writemask => 16#0B72#, Depth_Clear_Value => 16#0B73#, Depth_Func => 16#0B74#, Stencil_Test => 16#0B90#, Stencil_Clear_Value => 16#0B91#, Stencil_Func => 16#0B92#, Stencil_Value_Mask => 16#0B93#, Stencil_Fail => 16#0B94#, Stencil_Pass_Depth_Fail => 16#0B95#, Stencil_Pass_Depth_Pass => 16#0B96#, Stencil_Ref => 16#0B97#, Stencil_Writemask => 16#0B98#, Viewport => 16#0BA2#, Dither => 16#0BD0#, Blend_Dst => 16#0BE0#, Blend_Src => 16#0BE1#, Blend => 16#0BE2#, Logic_Op_Mode => 16#0BF0#, Color_Logic_Op => 16#0BF2#, Draw_Buffer => 16#0C01#, Read_Buffer => 16#0C02#, Scissor_Box => 16#0C10#, Scissor_Test => 16#0C11#, Color_Clear_Value => 16#0C22#, Color_Writemask => 16#0C23#, Doublebuffer => 16#0C32#, Stereo => 16#0C33#, Line_Smooth_Hint => 16#0C52#, Polygon_Smooth_Hint => 16#0C53#, Unpack_Swap_Bytes => 16#0CF0#, Unpack_Lsb_First => 16#0CF1#, Unpack_Row_Length => 16#0CF2#, Unpack_Skip_Rows => 16#0CF3#, Unpack_Skip_Pixels => 16#0CF4#, Unpack_Alignment => 16#0CF5#, Pack_Swap_Bytes => 16#0D00#, Pack_Lsb_First => 16#0D01#, Pack_Row_Length => 16#0D02#, Pack_Skip_Rows => 16#0D03#, Pack_Skip_Pixels => 16#0D04#, Pack_Alignment => 16#0D05#, Max_Clip_Distances => 16#0D32#, Max_Texture_Size => 16#0D33#, Max_Viewport_Dims => 16#0D3A#, Subpixel_Bits => 16#0D50#, Texture_1D => 16#0DE0#, Texture_2D => 16#0DE1#, Blend_Color => 16#8005#, Blend_Equation_RGB => 16#8009#, Pack_Skip_Images => 16#806B#, Pack_Image_Height => 16#806C#, Unpack_Skip_Images => 16#806D#, Unpack_Image_Height => 16#806E#, Blend_Dst_RGB => 16#80C8#, Blend_Src_RGB => 16#80C9#, Blend_Dst_Alpha => 16#80CA#, Blend_Src_Alpha => 16#80CB#, Major_Version => 16#821B#, Minor_Version => 16#821C#, Num_Extensions => 16#821D#, Num_Shading_Language_Versions => 16#82E9#, Aliased_Line_Width_Range => 16#846E#, Active_Texture => 16#84E0#, Max_Texture_Max_Anisotropy => 16#84FF#, Stencil_Back_Func => 16#8800#, Stencil_Back_Fail => 16#8801#, Stencil_Back_Pass_Depth_Fail => 16#8802#, Stencil_Back_Pass_Depth_Pass => 16#8803#, Blend_Equation_Alpha => 16#883D#, Max_Combined_Texture_Image_Units => 16#8B4D#, Min_Sample_Shading_Value => 16#8C37#, Stencil_Back_Ref => 16#8CA3#, Stencil_Back_Value_Mask => 16#8CA4#, Stencil_Back_Writemask => 16#8CA5#, Timestamp => 16#8E28#, Max_Debug_Message_Length => 16#9143#, Debug_Logged_Messages => 16#9145#, Max_Framebuffer_Width => 16#9315#, Max_Framebuffer_Height => 16#9316#, Max_Framebuffer_Layers => 16#9317#, Max_Framebuffer_Samples => 16#9318#); for Parameter'Size use Low_Level.Enum'Size; for String_Parameter use (Vendor => 16#1F00#, Renderer => 16#1F01#, Version => 16#1F02#, Extensions => 16#1F03#, Shading_Language_Version => 16#8B8C#); for String_Parameter'Size use Low_Level.Enum'Size; for Renderbuffer_Parameter use (Width => 16#8D42#, Height => 16#8D43#, Internal_Format => 16#8D44#, Red_Size => 16#8D50#, Green_Size => 16#8D51#, Blue_Size => 16#8D52#, Alpha_Size => 16#8D53#, Depth_Size => 16#8D54#, Stencil_Size => 16#8D55#); for Renderbuffer_Parameter'Size use Low_Level.Enum'Size; end GL.Enums.Getter;
Remove some enums in GL.Enums.Getter deprecated since OpenGL 3
gl: Remove some enums in GL.Enums.Getter deprecated since OpenGL 3 Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
08aac8f66d0e0f02f3b62f52ea3b7b064a469bfd
src/util-strings.adb
src/util-strings.adb
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Returns True if the source string ends with the given suffix. -- ------------------------------ function Ends_With (Source : in String; Suffix : in String) return Boolean is begin return Source'Length >= Suffix'Length and then Source (Source'Last - Suffix'Length + 1 .. Source'Last) = Suffix; end Ends_With; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Returns True if the source string ends with the given suffix. -- ------------------------------ function Ends_With (Source : in String; Suffix : in String) return Boolean is begin return Source'Length >= Suffix'Length and then Source (Source'Last - Suffix'Length + 1 .. Source'Last) = Suffix; end Ends_With; -- ------------------------------ -- Returns True if the source contains the pattern. -- ------------------------------ function Contains (Source : in String; Pattern : in String) return Boolean is begin return Ada.Strings.Fixed.Index (Source, Pattern) /= 0; end Contains; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
Implement the Contains function
Implement the Contains function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
32a3f077301fb0a215c6d2f3e190fe9b9a348e45
testcases/iterate/iterate.adb
testcases/iterate/iterate.adb
with AdaBase.Results.Sets; with Connect; with CommonText; with Ada.Text_IO; procedure Iterate is package CON renames Connect; package TIO renames Ada.Text_IO; package AR renames AdaBase.Results; package CT renames CommonText; fruit : aliased AR.textual; color : aliased AR.textual; calories : aliased AR.nbyte2; dashes : String (1 .. 50) := (others => '='); procedure list_fruit; procedure list_hockey_teams (row : AR.Sets.DataRow_Access); procedure list_fruit is pair : String := CT.USS (fruit) & " (" & CT.USS (color) & ")"; plen : Natural := pair'Length; zone : String (1 .. 20) := (others => ' '); begin zone (1 .. plen) := pair; TIO.Put_Line (zone & " contains" & calories'Img & " calories"); end list_fruit; procedure list_hockey_teams (row : AR.Sets.DataRow_Access) is begin TIO.Put_Line (row.column ("city").as_string & " " & row.column ("mascot").as_string & " (" & row.column ("abbreviation").as_string & ")"); end list_hockey_teams; begin begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; begin CON.STMT := CON.DR.query_select (tables => "fruits", columns => "fruit, calories, color", conditions => "calories >= 50", order => "calories"); CON.STMT.bind ("fruit", fruit'Unchecked_Access); CON.STMT.bind ("calories", calories'Unchecked_Access); CON.STMT.bind ("color", color'Unchecked_Access); TIO.Put_Line ("Demonstrate STMT.iterate (query + bound variables)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of fruit the contain at least 50 calories"); TIO.Put_Line (dashes); CON.STMT.iterate (process => list_fruit'Access); end; begin CON.STMT := CON.DR.prepare_select (tables => "nhl_teams", columns => "*", conditions => "city LIKE :pattern", order => "city"); TIO.Put_Line (""); TIO.Put_Line ("Demonstrate STMT.iterate (prepare + data access)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of NHL teams in locations starting with 'C'"); TIO.Put_Line (dashes); CON.STMT.assign ("pattern", "C%"); if CON.STMT.execute then CON.STMT.iterate (process => list_hockey_teams'Access); end if; end; CON.DR.disconnect; end Iterate;
with AdaBase.Results.Sets; with Connect; with CommonText; with Ada.Text_IO; procedure Iterate is package CON renames Connect; package TIO renames Ada.Text_IO; package AR renames AdaBase.Results; package CT renames CommonText; fruit : aliased AR.textual; color : aliased AR.textual; calories : aliased AR.nbyte2; dashes : String (1 .. 50) := (others => '='); procedure list_fruit; procedure list_hockey_teams (row : AR.Sets.DataRow); procedure list_fruit is pair : String := CT.USS (fruit) & " (" & CT.USS (color) & ")"; plen : Natural := pair'Length; zone : String (1 .. 20) := (others => ' '); begin zone (1 .. plen) := pair; TIO.Put_Line (zone & " contains" & calories'Img & " calories"); end list_fruit; procedure list_hockey_teams (row : AR.Sets.DataRow) is begin TIO.Put_Line (row.column ("city").as_string & " " & row.column ("mascot").as_string & " (" & row.column ("abbreviation").as_string & ")"); end list_hockey_teams; begin begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare stmt : CON.Stmt_Type := CON.DR.query_select (tables => "fruits", columns => "fruit, calories, color", conditions => "calories >= 50", order => "calories"); begin stmt.bind ("fruit", fruit'Unchecked_Access); stmt.bind ("calories", calories'Unchecked_Access); stmt.bind ("color", color'Unchecked_Access); TIO.Put_Line ("Demonstrate STMT.iterate (query + bound variables)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of fruit the contain at least 50 calories"); TIO.Put_Line (dashes); stmt.iterate (process => list_fruit'Access); end; declare stmt : CON.Stmt_Type := CON.DR.prepare_select (tables => "nhl_teams", columns => "*", conditions => "city LIKE :pattern", order => "city"); begin TIO.Put_Line (""); TIO.Put_Line ("Demonstrate STMT.iterate (prepare + data access)"); TIO.Put_Line (dashes); TIO.Put_Line ("List of NHL teams in locations starting with 'C'"); TIO.Put_Line (dashes); stmt.assign ("pattern", "C%"); if stmt.execute then stmt.iterate (process => list_hockey_teams'Access); end if; end; CON.DR.disconnect; end Iterate;
fix iterate test case
fix iterate test case
Ada
isc
jrmarino/AdaBase
f8c59555c4cb2305e119d8aadefeb84f540c0cb7
awa/src/aws/awa-mail-clients-aws_smtp.adb
awa/src/aws/awa-mail-clients-aws_smtp.adb
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email to {0}", ""); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
Update the log if the mail is disabled
Update the log if the mail is disabled
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
298150466ed925cd1a6bb984d98534c59ce6a15f
src/util-commands-parsers-gnat_parser.adb
src/util-commands-parsers-gnat_parser.adb
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GNAT.Command_Line.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GNAT.Command_Line.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GNAT.Command_Line.Initialize_Option_Scan (Parser, Params); GNAT.Command_Line.Getopt (Config => Config, Parser => Parser); loop declare S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser); begin exit when S'Length = 0; Cmd_Args.List.Append (S); end; end loop; Process (Cmd_Args); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); raise; end; else Process (Args); end if; end Execute; end Util.Commands.Parsers.GNAT_Parser;
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GNAT.Command_Line.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GNAT.Command_Line.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GNAT.Command_Line.Initialize_Option_Scan (Parser, Params); GNAT.Command_Line.Getopt (Config => Config, Parser => Parser); loop declare S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser); begin exit when S'Length = 0; Cmd_Args.List.Append (S); end; end loop; Process (Cmd_Args); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); raise; end; else Process (Args); end if; end Execute; procedure Usage (Name : in String; Config : in out Config_Type) is begin GNAT.Command_Line.Set_Usage (Config, Usage => Name & " [switches] [arguments]"); GNAT.Command_Line.Display_Help (Config); end Usage; end Util.Commands.Parsers.GNAT_Parser;
Implement Usage procedure to report the command usage
Implement Usage procedure to report the command usage
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c3600aa126e6ecf24ccb986658a60e1c529df095
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
Add the Filter parameter to the Find operation
Add the Filter parameter to the Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
bbdb38624e2601dd132b3c44487fc0d15fea0b37
src/atlas-server.adb
src/atlas-server.adb
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Commands; with AWS.Net.SSL; with Servlet.Server.Web; with AWA.Setup.Applications; with AWA.Commands.Drivers; with AWA.Commands.Start; with AWA.Commands.Setup; with AWA.Commands.Stop; with AWA.Commands.List; with AWA.Commands.Info; with ADO.Drivers; -- with ADO.Sqlite; -- with ADO.Mysql; -- with ADO.Postgresql; with Atlas.Applications; procedure Atlas.Server is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "atlas", Container_Type => Servlet.Server.Web.AWS_Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); package Info_Command is new AWA.Commands.Info (Server_Commands); package Setup_Command is new AWA.Commands.Setup (Start_Command); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : Servlet.Server.Web.AWS_Container renames Server_Commands.WS; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; begin -- Initialize the database drivers (all of them or specific ones). ADO.Drivers.Initialize; -- ADO.Sqlite.Initialize; -- ADO.Mysql.Initialize; -- ADO.Postgresql.Initialize; WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); 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; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Server_Commands.Run (Context, Arguments); exception when E : others => Context.Print (E); end Atlas.Server;
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018, 2019, 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.Log.Loggers; with Util.Commands; with AWS.Net.SSL; with Servlet.Server.Web; with AWA.Commands.Drivers; with AWA.Commands.Start; with AWA.Commands.Setup; with AWA.Commands.Stop; with AWA.Commands.List; with AWA.Commands.Info; with ADO.Drivers; -- with ADO.Sqlite; -- with ADO.Mysql; -- with ADO.Postgresql; with Atlas.Applications; procedure Atlas.Server is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "atlas", Container_Type => Servlet.Server.Web.AWS_Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); package Info_Command is new AWA.Commands.Info (Server_Commands); package Setup_Command is new AWA.Commands.Setup (Start_Command); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : Servlet.Server.Web.AWS_Container renames Server_Commands.WS; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; begin -- Initialize the database drivers (all of them or specific ones). ADO.Drivers.Initialize; -- ADO.Sqlite.Initialize; -- ADO.Mysql.Initialize; -- ADO.Postgresql.Initialize; WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); 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; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Server_Commands.Run (Context, Arguments); exception when E : others => Context.Print (E); end Atlas.Server;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/atlas
361ad23abdc2a7db6132ea9674086d0c9cd2f3a8
mat/src/memory/mat-memory-tools.adb
mat/src/memory/mat-memory-tools.adb
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is pragma Unreferenced (Addr); Pos : constant Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map) is procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Count (Thread : in MAT.Types.Target_Thread_Ref; Info : in out Memory_Info); procedure Update_Count (Thread : in MAT.Types.Target_Thread_Ref; Info : in out Memory_Info) is pragma Unreferenced (Thread); Size : constant MAT.Types.Target_Size := Slot.Size; begin Info.Alloc_Count := Info.Alloc_Count + 1; if Size < Info.Min_Slot_Size then Info.Min_Slot_Size := Size; end if; if Size > Info.Max_Slot_Size then Info.Max_Slot_Size := Size; end if; if Addr < Info.Min_Addr then Info.Min_Addr := Addr; end if; if Addr + Size > Info.Max_Addr then Info.Max_Addr := Addr + Size; end if; Info.Total_Size := Info.Total_Size + Size; end Update_Count; Pos : constant Memory_Info_Cursor := Threads.Find (Slot.Thread); begin if Memory_Info_Maps.Has_Element (Pos) then Threads.Update_Element (Pos, Update_Count'Access); else declare Info : Memory_Info; begin Info.Total_Size := Slot.Size; Info.Alloc_Count := 1; Info.Min_Slot_Size := Slot.Size; Info.Max_Slot_Size := Slot.Size; Info.Min_Addr := Addr; Info.Max_Addr := Addr + Slot.Size; Threads.Insert (Slot.Thread, Info); end; end if; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Thread_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if MAT.Expressions.Is_Selected (Filter, Addr, Slot) then Into.Insert (Addr, Slot); end if; end Collect; Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; begin -- If there was no slot with the ceiling From address, we have to start from the last -- node because the memory slot may intersect our region. if not Allocation_Maps.Has_Element (Iter) then Iter := Memory.Last; if not Allocation_Maps.Has_Element (Iter) then return; end if; Addr := Allocation_Maps.Key (Iter); Size := Allocation_Maps.Element (Iter).Size; if Addr + Size < From then return; end if; end if; -- Move backward until the previous memory slot does not overlap anymore our region. -- In theory, going backward once is enough but if there was a target malloc issue, -- several malloc may overlap the same region (which is bad for the target). loop Pos := Allocation_Maps.Previous (Iter); exit when not Allocation_Maps.Has_Element (Pos); Addr := Allocation_Maps.Key (Pos); Size := Allocation_Maps.Element (Pos).Size; exit when Addr + Size < From; Iter := Pos; end loop; -- Add the memory slots until we moved to the end of the region. while Allocation_Maps.Has_Element (Iter) loop Addr := Allocation_Maps.Key (Iter); exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Allocation_Maps.Query_Element (Iter, Collect'Access); end if; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is pragma Unreferenced (Addr); Pos : constant Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in MAT.Memory.Allocation_Map; Threads : in out Memory_Info_Map) is procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Count (Thread : in MAT.Types.Target_Thread_Ref; Info : in out Memory_Info); procedure Update_Count (Thread : in MAT.Types.Target_Thread_Ref; Info : in out Memory_Info) is pragma Unreferenced (Thread); Size : constant MAT.Types.Target_Size := Slot.Size; begin Info.Alloc_Count := Info.Alloc_Count + 1; if Size < Info.Min_Slot_Size then Info.Min_Slot_Size := Size; end if; if Size > Info.Max_Slot_Size then Info.Max_Slot_Size := Size; end if; if Addr < Info.Min_Addr then Info.Min_Addr := Addr; end if; if Addr + Size > Info.Max_Addr then Info.Max_Addr := Addr + Size; end if; Info.Total_Size := Info.Total_Size + Size; end Update_Count; Pos : constant Memory_Info_Cursor := Threads.Find (Slot.Thread); begin if Memory_Info_Maps.Has_Element (Pos) then Threads.Update_Element (Pos, Update_Count'Access); else declare Info : Memory_Info; begin Info.Total_Size := Slot.Size; Info.Alloc_Count := 1; Info.Min_Slot_Size := Slot.Size; Info.Max_Slot_Size := Slot.Size; Info.Min_Addr := Addr; Info.Max_Addr := Addr + Slot.Size; Threads.Insert (Slot.Thread, Info); end; end if; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in MAT.Memory.Allocation_Map; Level : in Natural; Frames : in out Frame_Info_Map) is procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Count (Frame_Addr : in MAT.Types.Target_Addr; Info : in out Frame_Info); procedure Update_Count (Frame_Addr : in MAT.Types.Target_Addr; Info : in out Frame_Info) is pragma Unreferenced (Frame_Addr); Size : constant MAT.Types.Target_Size := Slot.Size; begin Info.Memory.Alloc_Count := Info.Memory.Alloc_Count + 1; if Size < Info.Memory.Min_Slot_Size then Info.Memory.Min_Slot_Size := Size; end if; if Size > Info.Memory.Max_Slot_Size then Info.Memory.Max_Slot_Size := Size; end if; if Addr < Info.Memory.Min_Addr then Info.Memory.Min_Addr := Addr; end if; if Addr + Size > Info.Memory.Max_Addr then Info.Memory.Max_Addr := Addr + Size; end if; Info.Memory.Total_Size := Info.Memory.Total_Size + Size; end Update_Count; Frame : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame, Level); Pos : Frame_Info_Cursor; begin for I in Frame'Range loop Pos := Frames.Find (Frame (I)); if Frame_Info_Maps.Has_Element (Pos) then Frames.Update_Element (Pos, Update_Count'Access); else declare Info : Frame_Info; begin Info.Thread := Slot.Thread; Info.Memory.Total_Size := Slot.Size; Info.Memory.Alloc_Count := 1; Info.Memory.Min_Slot_Size := Slot.Size; Info.Memory.Max_Slot_Size := Slot.Size; Info.Memory.Min_Addr := Addr; Info.Memory.Max_Addr := Addr + Slot.Size; Frames.Insert (Frame (I), Info); end; end if; end loop; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if MAT.Expressions.Is_Selected (Filter, Addr, Slot) then Into.Insert (Addr, Slot); end if; end Collect; Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; begin -- If there was no slot with the ceiling From address, we have to start from the last -- node because the memory slot may intersect our region. if not Allocation_Maps.Has_Element (Iter) then Iter := Memory.Last; if not Allocation_Maps.Has_Element (Iter) then return; end if; Addr := Allocation_Maps.Key (Iter); Size := Allocation_Maps.Element (Iter).Size; if Addr + Size < From then return; end if; end if; -- Move backward until the previous memory slot does not overlap anymore our region. -- In theory, going backward once is enough but if there was a target malloc issue, -- several malloc may overlap the same region (which is bad for the target). loop Pos := Allocation_Maps.Previous (Iter); exit when not Allocation_Maps.Has_Element (Pos); Addr := Allocation_Maps.Key (Pos); Size := Allocation_Maps.Element (Pos).Size; exit when Addr + Size < From; Iter := Pos; end loop; -- Add the memory slots until we moved to the end of the region. while Allocation_Maps.Has_Element (Iter) loop Addr := Allocation_Maps.Key (Iter); exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Allocation_Maps.Query_Element (Iter, Collect'Access); end if; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
Implement the Frame_Information procedure
Implement the Frame_Information procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b9c2b99a99e84a3512d1e8a8ca2dc6ac7ce4299b
matp/regtests/mat-targets-tests.ads
matp/regtests/mat-targets-tests.ads
----------------------------------------------------------------------- -- mat-targets-tests -- Unit tests for MAT targets -- 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.Tests; package MAT.Targets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); end MAT.Targets.Tests;
----------------------------------------------------------------------- -- mat-targets-tests -- Unit tests for MAT targets -- 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.Tests; package MAT.Targets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); -- Test various type conversions. procedure Test_Conversions (T : in out Test); end MAT.Targets.Tests;
Declare the Test_Conversions procedure
Declare the Test_Conversions procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2aa4accca6c7d12816d835255842b10a81e4f755
src/gen-commands.adb
src/gen-commands.adb
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Configs; with Gen.Commands.Generate; with Gen.Commands.Project; with Gen.Commands.Page; with Gen.Commands.Layout; with Gen.Commands.Model; with Gen.Commands.Propset; with Gen.Commands.Database; with Gen.Commands.Info; with Gen.Commands.Distrib; with Gen.Commands.Plugins; with Gen.Commands.Docs; with Util.Log.Loggers; package body Gen.Commands is -- ------------------------------ -- Print dynamo short usage. -- ------------------------------ procedure Short_Help_Usage is use Ada.Text_IO; begin New_Line; Put ("Type '"); Put (Ada.Command_Line.Command_Name); Put_Line (" help' for the list of commands."); end Short_Help_Usage; -- Generate command. Generate_Cmd : aliased Gen.Commands.Generate.Command; -- Create project command. Create_Project_Cmd : aliased Gen.Commands.Project.Command; -- Add page command. Add_Page_Cmd : aliased Gen.Commands.Page.Command; -- Add layout command. Add_Layout_Cmd : aliased Gen.Commands.Layout.Command; -- Add model command. Add_Model_Cmd : aliased Gen.Commands.Model.Command; -- Sets a property on the dynamo.xml project. Propset_Cmd : aliased Gen.Commands.Propset.Command; -- Create database command. Database_Cmd : aliased Gen.Commands.Database.Command; -- Project information command. Info_Cmd : aliased Gen.Commands.Info.Command; -- Distrib command. Dist_Cmd : aliased Gen.Commands.Distrib.Command; -- Create plugin command. Create_Plugin_Cmd : aliased Gen.Commands.Plugins.Command; -- Documentation command. Doc_Plugin_Cmd : aliased Gen.Commands.Docs.Command; -- Help command. Help_Cmd : aliased Drivers.Help_Command_Type; begin Driver.Set_Description (Gen.Configs.RELEASE); Driver.Set_Usage ("[-v] [-o directory] [-t templates] {command} {arguments}" & ASCII.LF & "where:" & ASCII.LF & " -v Print the version, configuration and installation paths" & ASCII.LF & " -o directory Directory where the Ada mapping files are generated" & ASCII.LF & " -t templates Directory where the Ada templates are defined" & ASCII.LF & " -c dir Directory where the Ada templates " & "and configurations are defined"); Driver.Add_Command (Name => "help", Command => Help_Cmd'Access); Driver.Add_Command (Name => "generate", Command => Generate_Cmd'Access); Driver.Add_Command (Name => "create-project", Command => Create_Project_Cmd'Access); Driver.Add_Command (Name => "add-page", Command => Add_Page_Cmd'Access); Driver.Add_Command (Name => "add-layout", Command => Add_Layout_Cmd'Access); Driver.Add_Command (Name => "add-model", Command => Add_Model_Cmd'Access); Driver.Add_Command (Name => "propset", Command => Propset_Cmd'Access); Driver.Add_Command (Name => "create-database", Command => Database_Cmd'Access); Driver.Add_Command (Name => "create-plugin", Command => Create_Plugin_Cmd'Access); Driver.Add_Command (Name => "dist", Command => Dist_Cmd'Access); Driver.Add_Command (Name => "info", Command => Info_Cmd'Access); Driver.Add_Command (Name => "build-doc", Command => Doc_Plugin_Cmd'Access); end Gen.Commands;
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- Copyright (C) 2011, 2012, 2017, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Configs; with Gen.Commands.Generate; with Gen.Commands.Project; with Gen.Commands.Page; with Gen.Commands.Layout; with Gen.Commands.Model; with Gen.Commands.Propset; with Gen.Commands.Database; with Gen.Commands.Info; with Gen.Commands.Distrib; with Gen.Commands.Plugins; with Gen.Commands.Docs; package body Gen.Commands is -- ------------------------------ -- Print dynamo short usage. -- ------------------------------ procedure Short_Help_Usage is use Ada.Text_IO; begin New_Line; Put ("Type '"); Put (Ada.Command_Line.Command_Name); Put_Line (" help' for the list of commands."); end Short_Help_Usage; -- Generate command. Generate_Cmd : aliased Gen.Commands.Generate.Command; -- Create project command. Create_Project_Cmd : aliased Gen.Commands.Project.Command; -- Add page command. Add_Page_Cmd : aliased Gen.Commands.Page.Command; -- Add layout command. Add_Layout_Cmd : aliased Gen.Commands.Layout.Command; -- Add model command. Add_Model_Cmd : aliased Gen.Commands.Model.Command; -- Sets a property on the dynamo.xml project. Propset_Cmd : aliased Gen.Commands.Propset.Command; -- Create database command. Database_Cmd : aliased Gen.Commands.Database.Command; -- Project information command. Info_Cmd : aliased Gen.Commands.Info.Command; -- Distrib command. Dist_Cmd : aliased Gen.Commands.Distrib.Command; -- Create plugin command. Create_Plugin_Cmd : aliased Gen.Commands.Plugins.Command; -- Documentation command. Doc_Plugin_Cmd : aliased Gen.Commands.Docs.Command; -- Help command. Help_Cmd : aliased Drivers.Help_Command_Type; begin Driver.Set_Description (Gen.Configs.RELEASE); Driver.Set_Usage ("[-v] [-o directory] [-t templates] {command} {arguments}" & ASCII.LF & "where:" & ASCII.LF & " -v Print the version, configuration and installation paths" & ASCII.LF & " -o directory Directory where the Ada mapping files are generated" & ASCII.LF & " -t templates Directory where the Ada templates are defined" & ASCII.LF & " -c dir Directory where the Ada templates " & "and configurations are defined"); Driver.Add_Command (Name => "help", Command => Help_Cmd'Access); Driver.Add_Command (Name => "generate", Command => Generate_Cmd'Access); Driver.Add_Command (Name => "create-project", Command => Create_Project_Cmd'Access); Driver.Add_Command (Name => "add-page", Command => Add_Page_Cmd'Access); Driver.Add_Command (Name => "add-layout", Command => Add_Layout_Cmd'Access); Driver.Add_Command (Name => "add-model", Command => Add_Model_Cmd'Access); Driver.Add_Command (Name => "propset", Command => Propset_Cmd'Access); Driver.Add_Command (Name => "create-database", Command => Database_Cmd'Access); Driver.Add_Command (Name => "create-plugin", Command => Create_Plugin_Cmd'Access); Driver.Add_Command (Name => "dist", Command => Dist_Cmd'Access); Driver.Add_Command (Name => "info", Command => Info_Cmd'Access); Driver.Add_Command (Name => "build-doc", Command => Doc_Plugin_Cmd'Access); end Gen.Commands;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
b8849da1e369c4320ddc8d00e0a71bb898aa2d67
regtests/util-serialize-io-json-tests.adb
regtests/util-serialize-io-json-tests.adb
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 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.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); Check_Parse ("[{ ""person"":""\u2ABF""}]"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; end Util.Serialize.IO.JSON.Tests;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); Check_Parse ("[{ ""person"":""\u2ABF""}]"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; end Util.Serialize.IO.JSON.Tests;
Update parsing of JSON object
Update parsing of JSON object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
da792ff0cda558054ac91d95663f57cd70904b1e
awa/src/awa-modules-lifecycles.ads
awa/src/awa-modules-lifecycles.ads
----------------------------------------------------------------------- -- awa-modules-lifecycles -- Lifecycle listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Listeners.Lifecycles; generic type Element_Type (<>) is limited private; package AWA.Modules.Lifecycles is package LF is new Util.Listeners.Lifecycles (Element_Type); subtype Listener is LF.Listener; -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); pragma Inline (Notify_Create); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); pragma Inline (Notify_Update); -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); pragma Inline (Notify_Delete); end AWA.Modules.Lifecycles;
----------------------------------------------------------------------- -- awa-modules-lifecycles -- Lifecycle listeners -- Copyright (C) 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.Listeners.Lifecycles; generic type Element_Type (<>) is limited private; package AWA.Modules.Lifecycles is package LF is new Util.Listeners.Lifecycles (Element_Type); subtype Listener is LF.Listener; -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); procedure Notify_Create (Service : in AWA.Modules.Module'Class; Item : in Element_Type); pragma Inline (Notify_Create); -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); procedure Notify_Update (Service : in AWA.Modules.Module'Class; Item : in Element_Type); pragma Inline (Notify_Update); -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type); procedure Notify_Delete (Service : in AWA.Modules.Module'Class; Item : in Element_Type); pragma Inline (Notify_Delete); end AWA.Modules.Lifecycles;
Add Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
Add Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
f4d9124a8b928e96dfa7a55874e35c1c5ee4d405
src/asf-components-widgets-tabs.ads
src/asf-components-widgets-tabs.ads
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- 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 ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Tabs is COLLAPSIBLE_ATTR_NAME : constant String := "collapsible"; -- ------------------------------ -- UITab -- ------------------------------ -- The <b>UITab</b> component displays a tab component within a tab view. type UITab is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the tab start. overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tab close. overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- UITabView -- ------------------------------ -- The <b>UITabView</b> component displays a tab selection panel. type UITabView is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the tab list and prepare to render the tab contents. overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tab view close. overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Tabs;
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- 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 ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Tabs is COLLAPSIBLE_ATTR_NAME : constant String := "collapsible"; EFFECT_ATTR_NAME : constant String := "effect"; DURATION_ATTR_NAME : constant String := "duration"; -- ------------------------------ -- UITab -- ------------------------------ -- The <b>UITab</b> component displays a tab component within a tab view. type UITab is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the tab start. overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tab close. overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- UITabView -- ------------------------------ -- The <b>UITabView</b> component displays a tab selection panel. type UITabView is new ASF.Components.Html.UIHtmlComponent with null record; -- Render the tab list and prepare to render the tab contents. overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tab view close. overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Tabs;
Add effect and duration attributes
Add effect and duration attributes
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
072966372403a12a2c7c0b030e50eda91086c24d
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 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; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; procedure Load_Library (T : in out Test; Lib : out Handle); package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; Lib4 : Handle; Lib5 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; begin Lib4 := Util.Systems.DLLs.Load ("libz.so"); T.Assert (Lib4 /= Null_Handle, "Load operation returned null"); Lib := Lib4; exception when Load_Error => Lib4 := Null_Handle; end; begin Lib5 := Util.Systems.DLLs.Load ("libgmp.so"); T.Assert (Lib5 /= Null_Handle, "Load operation returned null"); Lib := Lib5; exception when Load_Error => Lib5 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle or Lib4 /= Null_Handle or Lib5 /= Null_Handle, "At least one Load operation should have succeeded"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 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; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; procedure Load_Library (T : in out Test; Lib : out Handle); package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; Lib4 : Handle; Lib5 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libgmp.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; begin Lib4 := Util.Systems.DLLs.Load ("libz.so"); T.Assert (Lib4 /= Null_Handle, "Load operation returned null"); Lib := Lib4; exception when Load_Error => Lib4 := Null_Handle; end; begin Lib5 := Util.Systems.DLLs.Load ("libgmp.so"); T.Assert (Lib5 /= Null_Handle, "Load operation returned null"); Lib := Lib5; exception when Load_Error => Lib5 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle or Lib4 /= Null_Handle or Lib5 /= Null_Handle, "At least one Load operation should have succeeded"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Fix execution of unit test on MacOS
Fix execution of unit test on MacOS
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
48144a4eea38c73d2cde0bea0a0566544b114d4c
src/util-commands-parsers-gnat_parser.adb
src/util-commands-parsers-gnat_parser.adb
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is Parser : GNAT.Command_Line.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GNAT.Command_Line.Initialize_Option_Scan (Parser, Params); GNAT.Command_Line.Getopt (Config => Config, Parser => Parser); loop declare S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser); begin exit when S'Length = 0; Cmd_Args.List.Append (S); end; end loop; Process (Cmd_Args); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); raise; end Execute; end Util.Commands.Parsers.GNAT_Parser;
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GNAT.Command_Line.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GNAT.Command_Line.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GNAT.Command_Line.Initialize_Option_Scan (Parser, Params); GNAT.Command_Line.Getopt (Config => Config, Parser => Parser); loop declare S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser); begin exit when S'Length = 0; Cmd_Args.List.Append (S); end; end loop; Process (Cmd_Args); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); raise; end; else Process (Args); end if; end Execute; end Util.Commands.Parsers.GNAT_Parser;
Fix execution of commands when the command does not configure anything with Getopt
Fix execution of commands when the command does not configure anything with Getopt
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
477e06aad18f082ce62856ac9f55fbc4ea00b704
awa/regtests/awa-jobs-services-tests.adb
awa/regtests/awa-jobs-services-tests.adb
----------------------------------------------------------------------- -- jobs-tests -- Unit tests for AWA jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with AWA.Jobs.Modules; with AWA.Services.Contexts; package body AWA.Jobs.Services.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests"); package Caller is new Util.Test_Caller (Test, "Jobs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register", Test_Job_Schedule'Access); end Add_Tests; procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Msg : constant String := Job.Get_Parameter ("message"); Cnt : constant Natural := Job.Get_Parameter ("count", 0); begin Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt)); end Work_1; procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is begin null; end Work_2; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Test_Job_Schedule (T : in out Test) is use type AWA.Jobs.Models.Job_Status_Type; J : AWA.Jobs.Services.Job_Type; M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module; Context : AWA.Services.Contexts.Service_Context; begin Context.Set_Context (AWA.Tests.Get_Application, null); M.Register (Definition => Services.Tests.Work_1_Definition.Factory'Access); J.Set_Parameter ("count", 1); Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param"); J.Set_Parameter ("message", "Hello"); Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param"); J.Schedule (Work_1_Definition.Factory); T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled"); -- for I in 1 .. 10 loop delay 0.1; end loop; end Test_Job_Schedule; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. overriding procedure Execute (Job : in out Test_Job) is begin null; end Execute; end AWA.Jobs.Services.Tests;
----------------------------------------------------------------------- -- jobs-tests -- Unit tests for AWA jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; with AWA.Jobs.Modules; with AWA.Services.Contexts; package body AWA.Jobs.Services.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests"); package Caller is new Util.Test_Caller (Test, "Jobs.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register", Test_Job_Schedule'Access); end Add_Tests; procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Msg : constant String := Job.Get_Parameter ("message"); Cnt : constant Natural := Job.Get_Parameter ("count", 0); begin Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt)); end Work_1; procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is begin null; end Work_2; -- ------------------------------ -- Test the job factory. -- ------------------------------ procedure Test_Job_Schedule (T : in out Test) is use type AWA.Jobs.Models.Job_Status_Type; J : AWA.Jobs.Services.Job_Type; M : AWA.Jobs.Modules.Job_Module_Access := AWA.Jobs.Modules.Get_Job_Module; Context : AWA.Services.Contexts.Service_Context; begin Context.Set_Context (AWA.Tests.Get_Application, null); M.Register (Definition => Services.Tests.Work_1_Definition.Factory); J.Set_Parameter ("count", 1); Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param"); J.Set_Parameter ("message", "Hello"); Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param"); J.Schedule (Work_1_Definition.Factory); T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled"); -- for I in 1 .. 10 loop delay 0.1; end loop; end Test_Job_Schedule; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. overriding procedure Execute (Job : in out Test_Job) is begin null; end Execute; end AWA.Jobs.Services.Tests;
Fix compilation of unit test
Fix compilation of unit test
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
f69443a947fac84a9f58d0859c9f6e0a709fa58b
src/base/commands/util-commands-drivers.adb
src/base/commands/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Strings.Formats; 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); function "-" (Message : in String) return String is (Translate (Message)) with Inline; -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); 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 out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Sets.Cursor); procedure Print (Position : in Command_Sets.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); Len : constant Natural := Length (Cmd.Name); begin if Natural (Column) < Len then Column := Ada.Text_IO.Positive_Count (Len); end if; end Compute_Size; procedure Print (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); begin Put (" "); Put (To_String (Cmd.Name)); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put_Line (Strings.Formats.Format (-("Type '{0} help {command}' for help " & "on a specific command."), Driver_Name)); Put_Line (-("Available subcommands:")); Command.Driver.List.Iterate (Process => Compute_Size'Access); 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); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; 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; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put (-("Invalid command")); end if; end; else Put (-("Usage: ")); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; 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.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Command); 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 Cmd : aliased Help_Command_Type; Pos : Command_Sets.Cursor; begin Cmd.Name := To_Unbounded_String (Name); Pos := Driver.List.Find (Cmd'Unchecked_Access); if Command_Sets.Has_Element (Pos) then return Command_Sets.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 procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error (-("Unknown command '{0}'"), Name); raise Not_Found; 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 out 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 out Handler_Command_Type; Name : in String; 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, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Strings.Formats; 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); function "-" (Message : in String) return String is (Translate (Message)) with Inline; -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); 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 out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Sets.Cursor); procedure Print (Position : in Command_Sets.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); Len : constant Natural := Length (Cmd.Name); begin if Natural (Column) < Len then Column := Ada.Text_IO.Positive_Count (Len); end if; end Compute_Size; procedure Print (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); begin Put (" "); Put (To_String (Cmd.Name)); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put_Line (Strings.Formats.Format (-("Type '{0} help {command}' for help " & "on a specific command."), Driver_Name)); Put_Line (-("Available subcommands:")); Command.Driver.List.Iterate (Process => Compute_Size'Access); 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); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; 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; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put (-("Invalid command")); end if; end; else Put (-("Usage: ")); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; 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.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Command); 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 Cmd : aliased Help_Command_Type; Pos : Command_Sets.Cursor; begin Cmd.Name := To_Unbounded_String (Name); Pos := Driver.List.Find (Cmd'Unchecked_Access); if Command_Sets.Has_Element (Pos) then return Command_Sets.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 procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error (-("unknown command '{0}'"), Name); raise Not_Found; 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 out 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 out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Fix error message
Fix error message
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a778c67adc76251a494ce4aab1d95635166e995a
src/base/commands/util-commands-drivers.adb
src/base/commands/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); 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 out 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, Context); 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 out 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; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; 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 procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; 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 out 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 out 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, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.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 out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); 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 out 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, Context); 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); raise Not_Found; else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out 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; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; 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 procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command '{0}'", Name); raise Not_Found; 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 out 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 out Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Raise the Not_Found exception in Execute and Help command when the command does not exist
Raise the Not_Found exception in Execute and Help command when the command does not exist
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
70d962750b146df9383b76492a93cc7a08f6c4f2
regtests/util-properties-tests.ads
regtests/util-properties-tests.ads
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 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.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); end Util.Properties.Tests;
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); procedure Test_Missing_Property (T : in out Test); end Util.Properties.Tests;
Declare the Test_Missing_Property procedure
Declare the Test_Missing_Property procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
df0f1184ea8f3ec1b0b4cd3fee492b7caaddbfeb
tools/druss-tools.adb
tools/druss-tools.adb
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Util.Log.Loggers; with Util.Properties; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Log_Config : Util.Properties.Manager; Config : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Strings.Unbounded.Unbounded_String; Debug : Boolean := False; Verbose : Boolean := False; Interactive : Boolean := False; First : Natural := 0; All_Args : Util.Commands.Default_Argument_List (0); Console : aliased Druss.Commands.Text_Consoles.Console_Type; Ctx : Druss.Commands.Context_Type; begin Log_Config.Set ("log4j.rootCategory", "DEBUG,console"); Log_Config.Set ("log4j.appender.console", "Console"); Log_Config.Set ("log4j.appender.console.level", "ERROR"); Log_Config.Set ("log4j.appender.console.layout", "level-message"); Log_Config.Set ("log4j.appender.stdout", "Console"); Log_Config.Set ("log4j.appender.stdout.level", "INFO"); Log_Config.Set ("log4j.appender.stdout.layout", "message"); Log_Config.Set ("log4j.logger.Util", "FATAL"); Log_Config.Set ("log4j.logger.Bbox", "FATAL"); Util.Log.Loggers.Initialize (Log_Config); Druss.Commands.Initialize; Ctx.Console := Console'Unchecked_Access; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d i o: c:") is when ASCII.NUL => exit; when 'c' => Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'o' => Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'i' => Interactive := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; if Verbose or Debug then Log_Config.Set ("log4j.appender.console.level", "INFO"); Log_Config.Set ("log4j.logger.Util", "WARN"); Log_Config.Set ("log4j.logger.Bbox", "ERR"); end if; if Debug then Log_Config.Set ("log4j.appender.console.level", "DEBUG"); end if; Util.Log.Loggers.Initialize (Log_Config); Druss.Config.Initialize (To_String (Config)); Util.Http.Clients.Curl.Register; -- Enter in the interactive mode. if Interactive then Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Interactive (Ctx); return; end if; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); Druss.Commands.Driver.Usage (All_Args); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); begin Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Util.Log.Loggers; with Util.Properties; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Log_Config : Util.Properties.Manager; Config : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Strings.Unbounded.Unbounded_String; Debug : Boolean := False; Verbose : Boolean := False; Interactive : Boolean := False; First : Natural := 0; All_Args : Util.Commands.Default_Argument_List (0); Console : aliased Druss.Commands.Text_Consoles.Console_Type; Ctx : Druss.Commands.Context_Type; begin Log_Config.Set ("log4j.rootCategory", "DEBUG,console"); Log_Config.Set ("log4j.appender.console", "Console"); Log_Config.Set ("log4j.appender.console.level", "ERROR"); Log_Config.Set ("log4j.appender.console.layout", "level-message"); Log_Config.Set ("log4j.appender.stdout", "Console"); Log_Config.Set ("log4j.appender.stdout.level", "INFO"); Log_Config.Set ("log4j.appender.stdout.layout", "message"); Log_Config.Set ("log4j.logger.Util", "FATAL"); Log_Config.Set ("log4j.logger.Bbox", "FATAL"); Util.Log.Loggers.Initialize (Log_Config); Druss.Commands.Initialize; Ctx.Console := Console'Unchecked_Access; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d i o: c:") is when ASCII.NUL => exit; when 'c' => Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'o' => Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'i' => Interactive := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; if Verbose or Debug then Log_Config.Set ("log4j.appender.console.level", "INFO"); Log_Config.Set ("log4j.logger.Util", "WARN"); Log_Config.Set ("log4j.logger.Bbox", "ERR"); end if; if Debug then Log_Config.Set ("log4j.appender.console.level", "DEBUG"); end if; Util.Log.Loggers.Initialize (Log_Config); Druss.Config.Initialize (To_String (Config)); Util.Http.Clients.Curl.Register; -- Enter in the interactive mode. if Interactive then Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Interactive (Ctx); return; end if; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); Druss.Commands.Driver.Usage (All_Args, Ctx); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); begin Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
Update to use latest Ada Util
Update to use latest Ada Util
Ada
apache-2.0
stcarrez/bbox-ada-api
9db0cac976cee7a97cc6e553e94f32db7690ae36
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_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 := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_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 := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Declare the Get_Grants function
Declare the Get_Grants function
Ada
apache-2.0
stcarrez/ada-security
2ad680e0fc57e965f605ae4bb1412a89fc2890bd
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 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; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; procedure Load_Library (T : in out Test; Lib : out Handle); package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; Lib4 : Handle; Lib5 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libgmp.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; begin Lib4 := Util.Systems.DLLs.Load ("libz.so"); T.Assert (Lib4 /= Null_Handle, "Load operation returned null"); Lib := Lib4; exception when Load_Error => Lib4 := Null_Handle; end; begin Lib5 := Util.Systems.DLLs.Load ("libgmp.so"); T.Assert (Lib5 /= Null_Handle, "Load operation returned null"); Lib := Lib5; exception when Load_Error => Lib5 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle or Lib4 /= Null_Handle or Lib5 /= Null_Handle, "At least one Load operation should have succeeded"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 2017, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; procedure Load_Library (T : in out Test; Lib : out Handle); package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; Lib4 : Handle; Lib5 : Handle; Lib6 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libgmp.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; begin Lib4 := Util.Systems.DLLs.Load ("libz.so"); T.Assert (Lib4 /= Null_Handle, "Load operation returned null"); Lib := Lib4; exception when Load_Error => Lib4 := Null_Handle; end; begin Lib5 := Util.Systems.DLLs.Load ("libgmp.so"); T.Assert (Lib5 /= Null_Handle, "Load operation returned null"); Lib := Lib5; exception when Load_Error => Lib5 := Null_Handle; end; begin Lib6 := Util.Systems.DLLs.Load ("libexpat-1.dll"); T.Assert (Lib6 /= Null_Handle, "Load operation returned null"); Lib := Lib6; exception when Load_Error => Lib6 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle or Lib4 /= Null_Handle or Lib5 /= Null_Handle or Lib6 /= Null_Handle, "At least one Load operation should have succeeded"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "__gmpf_cmp"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Update unit test for Windows
Update unit test for Windows
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
44283ed4ac968da9d5b795fc0bdab367de978702
regtests/security-oauth-servers-tests.ads
regtests/security-oauth-servers-tests.ads
----------------------------------------------------------------------- -- Security-oauth-servers-tests - Unit tests for server side OAuth -- 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.Tests; package Security.OAuth.Servers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the application manager. procedure Test_Application_Manager (T : in out Test); -- Test the user registration and verification. procedure Test_User_Verify (T : in out Test); -- Test the token operation that produces an access token from user/password. -- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant procedure Test_Token_Password (T : in out Test); end Security.OAuth.Servers.Tests;
----------------------------------------------------------------------- -- Security-oauth-servers-tests - Unit tests for server side OAuth -- 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.Tests; package Security.OAuth.Servers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the application manager. procedure Test_Application_Manager (T : in out Test); -- Test the user registration and verification. procedure Test_User_Verify (T : in out Test); -- Test the token operation that produces an access token from user/password. -- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant procedure Test_Token_Password (T : in out Test); -- Test the access token validation with invalid tokens (bad formed). procedure Test_Bad_Token (T : in out Test); end Security.OAuth.Servers.Tests;
Declare Test_Bad_Token procedure
Declare Test_Bad_Token procedure
Ada
apache-2.0
stcarrez/ada-security
3f421e224dbbbc7534db38ff3ab28b1f0bcca916
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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; private with Util.Strings.Maps; -- 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; Footer : in Boolean); -- Load from the file a list of link definitions which can be injected in the generated doc. -- This allows to avoid polluting the Ada code with external links. procedure Read_Links (Handler : in out Artifact; Path : in String); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); 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 record Links : Util.Strings.Maps.Map; end 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; Print_Footer : Boolean := True; 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; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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; private with Util.Strings.Maps; -- 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_INCLUDE_CONFIG : constant String := "include-config"; TAG_INCLUDE_BEAN : constant String := "include-bean"; TAG_INCLUDE_QUERY : constant String := "include-query"; TAG_INCLUDE_PERM : constant String := "include-permission"; 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; Footer : in Boolean); -- Load from the file a list of link definitions which can be injected in the generated doc. -- This allows to avoid polluting the Ada code with external links. procedure Read_Links (Handler : in out Artifact; Path : in String); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_INCLUDE_CONFIG, L_INCLUDE_BEAN, L_INCLUDE_PERMISSION, L_INCLUDE_QUERY, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); subtype Line_Include_Kind is Line_Kind range L_INCLUDE .. L_INCLUDE_QUERY; 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 Line_Group_Vector is array (Line_Include_Kind) of Line_Vectors.Vector; type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged record Links : Util.Strings.Maps.Map; end 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_Group_Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; 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; Mode : in Line_Include_Kind; 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; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
Add TAG_INCLUDE_CONFIG...TAG_INCLUDE_PERM for new tags keywords Declare Line_Group_Vector array of lines Use Line_Group_Vector for the document representation
Add TAG_INCLUDE_CONFIG...TAG_INCLUDE_PERM for new tags keywords Declare Line_Group_Vector array of lines Use Line_Group_Vector for the document representation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
05a84a4c90f18bf1ae227f64f9e15c98df0cab2b
src/gen-model-mappings.ads
src/gen-model-mappings.ads
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
Define the Map and Cursor subtypes
Define the Map and Cursor subtypes
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
c16b59eac4cc55dc56a2252ce046eae8a9993ca9
src/util-dates-formats.ads
src/util-dates-formats.ads
----------------------------------------------------------------------- -- util-dates-formats -- Date Format ala strftime -- Copyright (C) 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Properties; -- == Localized date formatting == -- The `Util.Dates.Formats` provides a date formatting operation similar to the -- Unix `strftime` or the `GNAT.Calendar.Time_IO`. The localization of month -- and day labels is however handled through `Util.Properties.Bundle` (similar to -- the Java world). Unlike `strftime`, this allows to have a multi-threaded application -- that reports dates in several languages. The `GNAT.Calendar.Time_IO` only supports -- English and this is the reason why it is not used here. -- -- The date pattern recognizes the following formats: -- -- | Format | Description | -- | --- | ---------- | -- | %a | The abbreviated weekday name according to the current locale. -- | %A | The full weekday name according to the current locale. -- | %b | The abbreviated month name according to the current locale. -- | %h | Equivalent to %b. (SU) -- | %B | The full month name according to the current locale. -- | %c | The preferred date and time representation for the current locale. -- | %C | The century number (year/100) as a 2-digit integer. (SU) -- | %d | The day of the month as a decimal number (range 01 to 31). -- | %D | Equivalent to %m/%d/%y -- | %e | Like %d, the day of the month as a decimal number, -- | | but a leading zero is replaced by a space. (SU) -- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99) -- | %G | The ISO 8601 week-based year -- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23). -- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12). -- | %j | The day of the year as a decimal number (range 001 to 366). -- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23); -- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12); -- | %m | The month as a decimal number (range 01 to 12). -- | %M | The minute as a decimal number (range 00 to 59). -- | %n | A newline character. (SU) -- | %p | Either "AM" or "PM" -- | %P | Like %p but in lowercase: "am" or "pm" -- | %r | The time in a.m. or p.m. notation. -- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) -- | %R | The time in 24 hour notation (%H:%M). -- | %s | The number of seconds since the Epoch, that is, -- | | since 1970\-01\-01 00:00:00 UTC. (TZ) -- | %S | The second as a decimal number (range 00 to 60). -- | %t | A tab character. (SU) -- | %T | The time in 24 hour notation (%H:%M:%S). (SU) -- | %u | The day of the week as a decimal, range 1 to 7, -- | | Monday being 1. See also %w. (SU) -- | %U | The week number of the current year as a decimal -- | | number, range 00 to 53 -- | %V | The ISO 8601 week number -- | %w | The day of the week as a decimal, range 0 to 6, -- | | Sunday being 0. See also %u. -- | %W | The week number of the current year as a decimal number, -- | | range 00 to 53 -- | %x | The preferred date representation for the current locale -- | | without the time. -- | %X | The preferred time representation for the current locale -- | | without the date. -- | %y | The year as a decimal number without a century (range 00 to 99). -- | %Y | The year as a decimal number including the century. -- | %z | The timezone as hour offset from GMT. -- | %Z | The timezone or name or abbreviation. -- -- The following strftime flags are ignored: -- -- %E Modifier: use alternative format, see below. (SU) -- %O Modifier: use alternative format, see below. (SU) -- -- SU: Single Unix Specification -- C99: C99 standard, POSIX.1-2001 -- -- See strftime (3) manual page package Util.Dates.Formats is -- Month labels. MONTH_NAME_PREFIX : constant String := "util.month"; -- Day labels. DAY_NAME_PREFIX : constant String := "util.day"; -- Short month/day suffix. SHORT_SUFFIX : constant String := ".short"; -- Long month/day suffix. LONG_SUFFIX : constant String := ".long"; -- The date time pattern name to be used for the %x representation. -- This property name is searched in the bundle to find the localized date time pattern. DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern"; -- The default date pattern for %c (English). DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y"; -- The date pattern to be used for the %x representation. -- This property name is searched in the bundle to find the localized date pattern. DATE_LOCALE_NAME : constant String := "util.date.pattern"; -- The default date pattern for %x (English). DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y"; -- The time pattern to be used for the %X representation. -- This property name is searched in the bundle to find the localized time pattern. TIME_LOCALE_NAME : constant String := "util.time.pattern"; -- The default time pattern for %X (English). TIME_DEFAULT_PATTERN : constant String := "%T %Y"; AM_NAME : constant String := "util.date.am"; PM_NAME : constant String := "util.date.pm"; AM_DEFAULT : constant String := "AM"; PM_DEFAULT : constant String := "PM"; -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- The date pattern is similar to the Unix <b>strftime</b> operation. -- -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Date_Record; Bundle : in Util.Properties.Manager'Class); -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class); function Format (Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) return String; -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String; Month : in Ada.Calendar.Month_Number; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String; Day : in Ada.Calendar.Formatting.Day_Name; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append a number with padding if necessary procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String; Value : in Natural; Padding : in Character; Length : in Natural := 2); -- Append the timezone offset procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String; Offset : in Ada.Calendar.Time_Zones.Time_Offset); end Util.Dates.Formats;
----------------------------------------------------------------------- -- util-dates-formats -- Date Format ala strftime -- Copyright (C) 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Properties; -- == Localized date formatting == -- The `Util.Dates.Formats` provides a date formatting operation similar to the -- Unix `strftime` or the `GNAT.Calendar.Time_IO`. The localization of month -- and day labels is however handled through `Util.Properties.Bundle` (similar to -- the Java world). Unlike `strftime`, this allows to have a multi-threaded application -- that reports dates in several languages. The `GNAT.Calendar.Time_IO` only supports -- English and this is the reason why it is not used here. -- -- The date pattern recognizes the following formats: -- -- | Format | Description | -- | --- | ---------- | -- | %a | The abbreviated weekday name according to the current locale. -- | %A | The full weekday name according to the current locale. -- | %b | The abbreviated month name according to the current locale. -- | %h | Equivalent to %b. (SU) -- | %B | The full month name according to the current locale. -- | %c | The preferred date and time representation for the current locale. -- | %C | The century number (year/100) as a 2-digit integer. (SU) -- | %d | The day of the month as a decimal number (range 01 to 31). -- | %D | Equivalent to %m/%d/%y -- | %e | Like %d, the day of the month as a decimal number, -- | | but a leading zero is replaced by a space. (SU) -- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99) -- | %G | The ISO 8601 week-based year -- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23). -- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12). -- | %j | The day of the year as a decimal number (range 001 to 366). -- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23); -- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12); -- | %m | The month as a decimal number (range 01 to 12). -- | %M | The minute as a decimal number (range 00 to 59). -- | %n | A newline character. (SU) -- | %p | Either "AM" or "PM" -- | %P | Like %p but in lowercase: "am" or "pm" -- | %r | The time in a.m. or p.m. notation. -- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) -- | %R | The time in 24 hour notation (%H:%M). -- | %s | The number of seconds since the Epoch, that is, -- | | since 1970\-01\-01 00:00:00 UTC. (TZ) -- | %S | The second as a decimal number (range 00 to 60). -- | %t | A tab character. (SU) -- | %T | The time in 24 hour notation (%H:%M:%S). (SU) -- | %u | The day of the week as a decimal, range 1 to 7, -- | | Monday being 1. See also %w. (SU) -- | %U | The week number of the current year as a decimal -- | | number, range 00 to 53 -- | %V | The ISO 8601 week number -- | %w | The day of the week as a decimal, range 0 to 6, -- | | Sunday being 0. See also %u. -- | %W | The week number of the current year as a decimal number, -- | | range 00 to 53 -- | %x | The preferred date representation for the current locale -- | | without the time. -- | %X | The preferred time representation for the current locale -- | | without the date. -- | %y | The year as a decimal number without a century (range 00 to 99). -- | %Y | The year as a decimal number including the century. -- | %z | The timezone as hour offset from GMT. -- | %Z | The timezone or name or abbreviation. -- -- The following strftime flags are ignored: -- -- | Format | Description | -- | --- | ---------- | -- | %E | Modifier: use alternative format, see below. (SU) -- | %O | Modifier: use alternative format, see below. (SU) -- -- SU: Single Unix Specification -- C99: C99 standard, POSIX.1-2001 -- -- See strftime (3) manual page -- -- To format and use the localize date, it is first necessary to get a bundle -- for the `dates` so that date elements are translated into the given locale. -- -- Factory : Util.Properties.Bundles.Loader; -- Bundle : Util.Properties.Bundles.Manager; -- ... -- Load_Bundle (Factory, "dates", "fr", Bundle); -- -- The date is formatted according to the pattern string described above. -- The bundle is used by the formatter to use the day and month names in the -- expected locale. -- -- Date : String := Util.Dates.Formats.Format (Pattern => Pattern, -- Date => Ada.Calendar.Clock, -- Bundle => Bundle); package Util.Dates.Formats is -- Month labels. MONTH_NAME_PREFIX : constant String := "util.month"; -- Day labels. DAY_NAME_PREFIX : constant String := "util.day"; -- Short month/day suffix. SHORT_SUFFIX : constant String := ".short"; -- Long month/day suffix. LONG_SUFFIX : constant String := ".long"; -- The date time pattern name to be used for the %x representation. -- This property name is searched in the bundle to find the localized date time pattern. DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern"; -- The default date pattern for %c (English). DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y"; -- The date pattern to be used for the %x representation. -- This property name is searched in the bundle to find the localized date pattern. DATE_LOCALE_NAME : constant String := "util.date.pattern"; -- The default date pattern for %x (English). DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y"; -- The time pattern to be used for the %X representation. -- This property name is searched in the bundle to find the localized time pattern. TIME_LOCALE_NAME : constant String := "util.time.pattern"; -- The default time pattern for %X (English). TIME_DEFAULT_PATTERN : constant String := "%T %Y"; AM_NAME : constant String := "util.date.am"; PM_NAME : constant String := "util.date.pm"; AM_DEFAULT : constant String := "AM"; PM_DEFAULT : constant String := "PM"; -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- The date pattern is similar to the Unix <b>strftime</b> operation. -- -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Date_Record; Bundle : in Util.Properties.Manager'Class); -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Append the formatted date in the <b>Into</b> string. procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class); function Format (Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) return String; -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String; Month : in Ada.Calendar.Month_Number; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String; Day : in Ada.Calendar.Formatting.Day_Name; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True); -- Append a number with padding if necessary procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String; Value : in Natural; Padding : in Character; Length : in Natural := 2); -- Append the timezone offset procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String; Offset : in Ada.Calendar.Time_Zones.Time_Offset); end Util.Dates.Formats;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f9727d35a3724cbd8477c62359ebddaece8de362
src/util-events-timers.ads
src/util-events-timers.ads
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Real_Time; private with Ada.Finalization; private with Util.Concurrent.Counters; -- == Timer Management == -- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have -- operations called on regular basis when a deadline has expired. It is very close to -- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility -- by allowing to have several timer lists that run independently. Unlike the GNAT -- implementation, this timer list management does not use tasks at all. The timer list -- can therefore be used in a mono-task environment by the main process task. Furthermore -- you can control your own task priority by having your own task that uses the timer list. -- -- The timer list is created by an instance of <tt>Timer_List</tt>: -- -- Manager : Util.Events.Timers.Timer_List; -- -- The timer list is protected against concurrent accesses so that timing events can be -- setup by a task but the timer handler is executed by another task. -- -- === Timer Creation === -- A timer handler is defined by implementing the <tt>Timer</tt> interface with the -- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows: -- -- type Timeout is new Timer with null record; -- overriding procedure Time_Handler (T : in out Timeout); -- -- My_Timeout : aliased Timeout; -- -- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler -- to be called as well as the deadline time. The timer instance is initialized as follows: -- -- T : Util.Events.Timers.Timer_Ref; -- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1)); -- -- === Timer Main Loop === -- Because the implementation does not impose any execution model, the timer management must -- be called regularly by some application's main loop. The <tt>Process</tt> procedure -- executes the timer handler that have ellapsed and it returns the deadline to wait for the -- next timer to execute. -- -- Deadline : Ada.Real_Time.Time; -- loop -- ... -- Manager.Process (Deadline); -- delay until Deadline; -- end loop; -- package Util.Events.Timers is type Timer_Ref is tagged private; -- The timer interface that must be implemented by applications. type Timer is limited interface; type Timer_Access is access all Timer'Class; -- The timer handler executed when the timer deadline has passed. procedure Time_Handler (T : in out Timer; Event : in out Timer_Ref'Class) is abstract; -- Repeat the timer. procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span); -- Cancel the timer. procedure Cancel (Event : in out Timer_Ref); -- Check if the timer is ready to be executed. function Is_Scheduled (Event : in Timer_Ref) return Boolean; -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time; type Timer_List is tagged limited private; -- Set a timer to be called at the given time. procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time); -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last); private type Timer_Manager; type Timer_Manager_Access is access all Timer_Manager; type Timer_Node; type Timer_Node_Access is access all Timer_Node; type Timer_Ref is new Ada.Finalization.Controlled with record Value : Timer_Node_Access; end record; overriding procedure Adjust (Object : in out Timer_Ref); overriding procedure Finalize (Object : in out Timer_Ref); type Timer_Node is limited record Next : Timer_Node_Access; Prev : Timer_Node_Access; List : Timer_Manager_Access; Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Handler : Timer_Access; Deadline : Ada.Real_Time.Time; end record; protected type Timer_Manager is -- Add a timer. procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time); -- Cancel a timer. procedure Cancel (Timer : in out Timer_Node_Access); -- Find the next timer to be executed or return the next deadline. procedure Find_Next (Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref); private List : Timer_Node_Access; end Timer_Manager; type Timer_List is new Ada.Finalization.Limited_Controlled with record Manager : aliased Timer_Manager; end record; overriding procedure Finalize (Object : in out Timer_List); end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Real_Time; private with Ada.Finalization; private with Util.Concurrent.Counters; -- == Timer Management == -- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have -- operations called on regular basis when a deadline has expired. It is very close to -- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility -- by allowing to have several timer lists that run independently. Unlike the GNAT -- implementation, this timer list management does not use tasks at all. The timer list -- can therefore be used in a mono-task environment by the main process task. Furthermore -- you can control your own task priority by having your own task that uses the timer list. -- -- The timer list is created by an instance of <tt>Timer_List</tt>: -- -- Manager : Util.Events.Timers.Timer_List; -- -- The timer list is protected against concurrent accesses so that timing events can be -- setup by a task but the timer handler is executed by another task. -- -- === Timer Creation === -- A timer handler is defined by implementing the <tt>Timer</tt> interface with the -- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows: -- -- type Timeout is new Timer with null record; -- overriding procedure Time_Handler (T : in out Timeout); -- -- My_Timeout : aliased Timeout; -- -- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler -- to be called as well as the deadline time. The timer instance is initialized as follows: -- -- T : Util.Events.Timers.Timer_Ref; -- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1)); -- -- === Timer Main Loop === -- Because the implementation does not impose any execution model, the timer management must -- be called regularly by some application's main loop. The <tt>Process</tt> procedure -- executes the timer handler that have ellapsed and it returns the deadline to wait for the -- next timer to execute. -- -- Deadline : Ada.Real_Time.Time; -- loop -- ... -- Manager.Process (Deadline); -- delay until Deadline; -- end loop; -- package Util.Events.Timers is type Timer_Ref is tagged private; -- The timer interface that must be implemented by applications. type Timer is limited interface; type Timer_Access is access all Timer'Class; -- The timer handler executed when the timer deadline has passed. procedure Time_Handler (T : in out Timer; Event : in out Timer_Ref'Class) is abstract; -- Repeat the timer. procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span); -- Cancel the timer. procedure Cancel (Event : in out Timer_Ref); -- Check if the timer is ready to be executed. function Is_Scheduled (Event : in Timer_Ref) return Boolean; -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time; type Timer_List is tagged limited private; -- Set a timer to be called at the given time. procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time); -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last); private type Timer_Manager; type Timer_Manager_Access is access all Timer_Manager; type Timer_Node; type Timer_Node_Access is access all Timer_Node; type Timer_Ref is new Ada.Finalization.Controlled with record Value : Timer_Node_Access; end record; overriding procedure Adjust (Object : in out Timer_Ref); overriding procedure Finalize (Object : in out Timer_Ref); type Timer_Node is limited record Next : Timer_Node_Access; Prev : Timer_Node_Access; List : Timer_Manager_Access; Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Handler : Timer_Access; Deadline : Ada.Real_Time.Time; end record; protected type Timer_Manager is -- Add a timer. procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time); -- Cancel a timer. procedure Cancel (Timer : in out Timer_Node_Access); -- Find the next timer to be executed before the given time or return the next deadline. procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref); private List : Timer_Node_Access; end Timer_Manager; type Timer_List is new Ada.Finalization.Limited_Controlled with record Manager : aliased Timer_Manager; end record; overriding procedure Finalize (Object : in out Timer_List); end Util.Events.Timers;
Update Find_Next to define the deadline to check as parameter
Update Find_Next to define the deadline to check as parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cbe8f9ec7cb36b8e5649e784bf36a5c9ce4f476f
mat/src/parser/mat-expressions-parser_io.ads
mat/src/parser/mat-expressions-parser_io.ads
----------------------------------------------------------------------- -- mat-expressions-parser_io -- Input IO for Lex parser -- 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.Expressions.lexer_dfa; with Ada.Text_IO; package MAT.Expressions.Parser_IO is use MAT.Expressions.lexer_dfa; user_output_file : Ada.Text_IO.File_Type; NULL_IN_INPUT : exception; AFLEX_INTERNAL_ERROR : exception; UNEXPECTED_LAST_MATCH : exception; PUSHBACK_OVERFLOW : exception; AFLEX_SCANNER_JAMMED : exception; type eob_action_type is (EOB_ACT_RESTART_SCAN, EOB_ACT_END_OF_FILE, EOB_ACT_LAST_MATCH); YY_END_OF_BUFFER_CHAR : constant Character := ASCII.NUL; -- number of characters read into yy_ch_buf yy_n_chars : Integer; -- true when we've seen an EOF for the current input file yy_eof_has_been_seen : Boolean; procedure Set_Input (Content : in String); procedure YY_INPUT (Buf : out MAT.Expressions.lexer_dfa.unbounded_character_array; Result : out Integer; Max_Size : in Integer); function yy_get_next_buffer return eob_action_type; function Input_Line return Ada.Text_IO.Count; function yywrap return Boolean; procedure Open_Input (Fname : in String); end MAT.Expressions.Parser_IO;
----------------------------------------------------------------------- -- mat-expressions-parser_io -- Input IO for Lex parser -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Expressions.Lexer_dfa; with Ada.Text_IO; package MAT.Expressions.Parser_IO is use MAT.Expressions.Lexer_dfa; user_output_file : Ada.Text_IO.File_Type; NULL_IN_INPUT : exception; AFLEX_INTERNAL_ERROR : exception; UNEXPECTED_LAST_MATCH : exception; PUSHBACK_OVERFLOW : exception; AFLEX_SCANNER_JAMMED : exception; type eob_action_type is (EOB_ACT_RESTART_SCAN, EOB_ACT_END_OF_FILE, EOB_ACT_LAST_MATCH); YY_END_OF_BUFFER_CHAR : constant Character := ASCII.NUL; -- number of characters read into yy_ch_buf yy_n_chars : Integer; -- true when we've seen an EOF for the current input file yy_eof_has_been_seen : Boolean; procedure Set_Input (Content : in String); procedure YY_INPUT (Buf : out MAT.Expressions.Lexer_dfa.unbounded_character_array; Result : out Integer; Max_Size : in Integer); function yy_get_next_buffer return eob_action_type; function Input_Line return Ada.Text_IO.Count; function yywrap return Boolean; procedure Open_Input (Fname : in String); end MAT.Expressions.Parser_IO;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cc6071a70e1c2983b91d0579bc06aa991e07bf2c
regtests/util-beans-objects-record_tests.adb
regtests/util-beans-objects-record_tests.adb
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- 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.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Objects.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J - 1); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Unchecked_Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
----------------------------------------------------------------------- -- util-beans-objects-record_tests -- Unit tests for objects.records package -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Util.Beans.Basic; with Util.Beans.Objects.Vectors; with Util.Beans.Objects.Records; package body Util.Beans.Objects.Record_Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Objects.Records"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records", Test_Record'Access); Caller.Add_Test (Suite, "Test Util.Beans.Basic", Test_Bean'Access); end Add_Tests; type Data is record Name : Unbounded_String; Value : Util.Beans.Objects.Object; end record; package Data_Bean is new Util.Beans.Objects.Records (Data); use type Data_Bean.Element_Type_Access; subtype Data_Access is Data_Bean.Element_Type_Access; procedure Test_Record (T : in out Test) is D : Data; begin D.Name := To_Unbounded_String ("testing"); D.Value := To_Object (Integer (23)); declare V : Object := Data_Bean.To_Object (D); P : constant Data_Access := Data_Bean.To_Element_Access (V); V2 : constant Object := V; begin T.Assert (not Is_Empty (V), "Object with data record should not be empty"); T.Assert (not Is_Null (V), "Object with data record should not be null"); T.Assert (P /= null, "To_Element_Access returned null"); Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same"); Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same"); V := Data_Bean.Create; declare D2 : constant Data_Access := Data_Bean.To_Element_Access (V); begin T.Assert (D2 /= null, "Null element"); D2.Name := To_Unbounded_String ("second test"); D2.Value := V2; end; V := Data_Bean.To_Object (D); end; end Test_Record; type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record Name : Unbounded_String; end record; type Bean_Type_Access is access all Bean_Type'Class; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object; overriding function Get_Value (Bean : in Bean_Type; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); elsif Name = "length" then return Util.Beans.Objects.To_Object (Length (Bean.Name)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; procedure Test_Bean (T : in out Test) is use Basic; Static : aliased Bean_Type; begin Static.Name := To_Unbounded_String ("Static"); -- Allocate dynamically several Bean_Type objects and drop the list. -- The memory held by internal proxy as well as the Bean_Type must be freed. -- The static bean should never be freed! for I in 1 .. 10 loop declare List : Util.Beans.Objects.Vectors.Vector; Value : Util.Beans.Objects.Object; Bean : Bean_Type_Access; P : access Readonly_Bean'Class; begin for J in 1 .. 1_000 loop if I = J then Value := To_Object (Static'Unchecked_Access, Objects.STATIC); List.Append (Value); end if; Bean := new Bean_Type; Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J)); Value := To_Object (Bean); List.Append (Value); end loop; -- Verify each bean of the list for J in 1 .. 1_000 + 1 loop Value := List.Element (J); -- Check some common status. T.Assert (not Is_Null (Value), "The value should hold a bean"); T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean"); T.Assert (not Is_Empty (Value), "The value should not be empty"); -- Check the bean access. P := To_Bean (Value); T.Assert (P /= null, "To_Bean returned null"); Bean := Bean_Type'Class (P.all)'Unchecked_Access; -- Check we have the good bean object. if I = J then Assert_Equals (T, "Static", To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); elsif J > I then Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); else Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name), "Bean at" & Integer'Image (J) & " is invalid"); end if; end loop; end; end loop; end Test_Bean; end Util.Beans.Objects.Record_Tests;
Fix the unit test now that Vectors package uses Positive type as index
Fix the unit test now that Vectors package uses Positive type as index
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1b2daf0dc33d2c1a48a5033dc27c8c74117b08b8
gnat/spark/gnatvsn.adb
gnat/spark/gnatvsn.adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T V S N -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2021, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Gnatvsn is ---------------------- -- Copyright_Holder -- ---------------------- function Copyright_Holder return String is begin return "Free Software Foundation, Inc."; end Copyright_Holder; ------------------------ -- Gnat_Free_Software -- ------------------------ function Gnat_Free_Software return String is begin return "This is free software; see the source for copying conditions." & ASCII.LF & "There is NO warranty; not even for MERCHANTABILITY or FITNESS" & " FOR A PARTICULAR PURPOSE."; end Gnat_Free_Software; ------------------------- -- Gnat_Version_String -- ------------------------- function Gnat_Version_String return String is begin return "12.0.0"; end Gnat_Version_String; end Gnatvsn;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T V S N -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2021, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Gnatvsn is ---------------------- -- Copyright_Holder -- ---------------------- function Copyright_Holder return String is begin return "Free Software Foundation, Inc."; end Copyright_Holder; ------------------------ -- Gnat_Free_Software -- ------------------------ function Gnat_Free_Software return String is begin return "This is free software; see the source for copying conditions." & ASCII.LF & "There is NO warranty; not even for MERCHANTABILITY or FITNESS" & " FOR A PARTICULAR PURPOSE."; end Gnat_Free_Software; ------------------------- -- Gnat_Version_String -- ------------------------- function Gnat_Version_String return String is begin return "12.0.0 20210712 (experimental)"; end Gnat_Version_String; end Gnatvsn;
use real-er version
spark: use real-er version
Ada
mit
1ma/dockertronics,1ma/dockertronics
6885c7cadeda28362ed3dabe26efa435013e94b6
src/model/gen-database-model.ads
src/model/gen-database-model.ads
----------------------------------------------------------------------- -- Gen.Database.Model -- Gen.Database.Model ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 305 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Basic.Lists; pragma Warnings (On, "unit * is not referenced"); package Gen.Database.Model is -- -------------------- -- Application Schema information -- -------------------- -- Create an object key for Schema. function Schema_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Schema from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Schema_Key (Id : in String) return ADO.Objects.Object_Key; type Schema_Ref is new ADO.Objects.Object_Ref with null record; Null_Schema : constant Schema_Ref; function "=" (Left, Right : Schema_Ref'Class) return Boolean; -- Set the model name procedure Set_Name (Object : in out Schema_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Name (Object : in out Schema_Ref; Value : in String); -- Get the model name function Get_Name (Object : in Schema_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Name (Object : in Schema_Ref) return String; -- Set the schema version procedure Set_Version (Object : in out Schema_Ref; Value : in Integer); -- Get the schema version function Get_Version (Object : in Schema_Ref) return Integer; -- Set the upgrade date procedure Set_Date (Object : in out Schema_Ref; Value : in ADO.Nullable_Time); -- Get the upgrade date function Get_Date (Object : in Schema_Ref) return ADO.Nullable_Time; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Schema_Ref; Session : in out ADO.Sessions.Session'Class; Id : in Ada.Strings.Unbounded.Unbounded_String); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Schema_Ref; Session : in out ADO.Sessions.Session'Class; Id : in Ada.Strings.Unbounded.Unbounded_String; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Schema_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Schema_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Schema_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (Item : in Schema_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition SCHEMA_TABLE : aliased constant ADO.Schemas.Class_Mapping; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Schema_Ref); -- Copy of the object. procedure Copy (Object : in Schema_Ref; Into : in out Schema_Ref); package Schema_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Schema_Ref, "=" => "="); subtype Schema_Vector is Schema_Vectors.Vector; procedure List (Object : in out Schema_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class); -- -------------------- -- information about the database -- -------------------- type Database_Info is tagged record -- the database name. Name : Ada.Strings.Unbounded.Unbounded_String; end record; package Database_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Database_Info, "=" => "="); subtype Database_Info_Vector is Database_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Database_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Database_List : constant ADO.Queries.Query_Definition_Access; Query_Table_List : constant ADO.Queries.Query_Definition_Access; Query_Create_Database : constant ADO.Queries.Query_Definition_Access; Query_Create_User_No_Password : constant ADO.Queries.Query_Definition_Access; Query_Create_User_With_Password : constant ADO.Queries.Query_Definition_Access; Query_Flush_Privileges : constant ADO.Queries.Query_Definition_Access; private SCHEMA_NAME : aliased constant String := "ADO_SCHEMA"; COL_0_1_NAME : aliased constant String := "NAME"; COL_1_1_NAME : aliased constant String := "VERSION"; COL_2_1_NAME : aliased constant String := "DATE"; SCHEMA_TABLE : aliased constant ADO.Schemas.Class_Mapping := (Count => 3, Table => SCHEMA_NAME'Access, Members => ( COL_0_1_NAME'Access, COL_1_1_NAME'Access, COL_2_1_NAME'Access ) ); Null_Schema : constant Schema_Ref := Schema_Ref'(ADO.Objects.Object_Ref with others => <>); type Schema_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_STRING, Of_Class => SCHEMA_TABLE'Access) with record Version : Integer; Date : ADO.Nullable_Time; end record; type Schema_Access is access all Schema_Impl; overriding procedure Destroy (Object : access Schema_Impl); overriding procedure Find (Object : in out Schema_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Schema_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Schema_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Schema_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Schema_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Schema_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Schema_Ref'Class; Impl : out Schema_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "create-database.xml", Sha1 => "5CCC0C05ECA7B8D6757ED08034015B1453C95014"); package Def_Databaseinfo_Database_List is new ADO.Queries.Loaders.Query (Name => "database-list", File => File_1.File'Access); Query_Database_List : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Database_List.Query'Access; package Def_Databaseinfo_Table_List is new ADO.Queries.Loaders.Query (Name => "table-list", File => File_1.File'Access); Query_Table_List : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Table_List.Query'Access; package Def_Databaseinfo_Create_Database is new ADO.Queries.Loaders.Query (Name => "create-database", File => File_1.File'Access); Query_Create_Database : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Create_Database.Query'Access; package Def_Databaseinfo_Create_User_No_Password is new ADO.Queries.Loaders.Query (Name => "create-user-no-password", File => File_1.File'Access); Query_Create_User_No_Password : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Create_User_No_Password.Query'Access; package Def_Databaseinfo_Create_User_With_Password is new ADO.Queries.Loaders.Query (Name => "create-user-with-password", File => File_1.File'Access); Query_Create_User_With_Password : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Create_User_With_Password.Query'Access; package Def_Databaseinfo_Flush_Privileges is new ADO.Queries.Loaders.Query (Name => "flush-privileges", File => File_1.File'Access); Query_Flush_Privileges : constant ADO.Queries.Query_Definition_Access := Def_Databaseinfo_Flush_Privileges.Query'Access; end Gen.Database.Model;
----------------------------------------------------------------------- -- Gen.Database.Model -- Gen.Database.Model ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Basic.Lists; pragma Warnings (On); package Gen.Database.Model is pragma Style_Checks ("-mr"); Query_Database_List : constant ADO.Queries.Query_Definition_Access; Query_Table_List : constant ADO.Queries.Query_Definition_Access; Query_Create_Database : constant ADO.Queries.Query_Definition_Access; Query_Create_User_No_Password : constant ADO.Queries.Query_Definition_Access; Query_Create_User_With_Password : constant ADO.Queries.Query_Definition_Access; Query_Flush_Privileges : constant ADO.Queries.Query_Definition_Access; private package File_1 is new ADO.Queries.Loaders.File (Path => "create-database.xml", Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543"); package Def_Database_List is new ADO.Queries.Loaders.Query (Name => "database-list", File => File_1.File'Access); Query_Database_List : constant ADO.Queries.Query_Definition_Access := Def_Database_List.Query'Access; package Def_Table_List is new ADO.Queries.Loaders.Query (Name => "table-list", File => File_1.File'Access); Query_Table_List : constant ADO.Queries.Query_Definition_Access := Def_Table_List.Query'Access; package Def_Create_Database is new ADO.Queries.Loaders.Query (Name => "create-database", File => File_1.File'Access); Query_Create_Database : constant ADO.Queries.Query_Definition_Access := Def_Create_Database.Query'Access; package Def_Create_User_No_Password is new ADO.Queries.Loaders.Query (Name => "create-user-no-password", File => File_1.File'Access); Query_Create_User_No_Password : constant ADO.Queries.Query_Definition_Access := Def_Create_User_No_Password.Query'Access; package Def_Create_User_With_Password is new ADO.Queries.Loaders.Query (Name => "create-user-with-password", File => File_1.File'Access); Query_Create_User_With_Password : constant ADO.Queries.Query_Definition_Access := Def_Create_User_With_Password.Query'Access; package Def_Flush_Privileges is new ADO.Queries.Loaders.Query (Name => "flush-privileges", File => File_1.File'Access); Query_Flush_Privileges : constant ADO.Queries.Query_Definition_Access := Def_Flush_Privileges.Query'Access; end Gen.Database.Model;
Rebuild the model files
Rebuild the model files
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2e24a44bd2beeca7f49455f26c2b58b282d01024
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Chmod, "chmod"); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; subtype File_Type is Util.Systems.Types.File_Type; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Chmod, "chmod"); -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer; pragma Import (C, Sys_Chdir, "chdir"); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
Declare Sys_Chdir function
Declare Sys_Chdir function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
33d52833eb2b8b6939f6604d04588c16e1a1bca3
src/http/aws/util-http-clients-web.adb
src/http/aws/util-http-clients-web.adb
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Put; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in AWS_Http_Manager; Http : in Client'Class; Timeout : in Duration) is begin AWS_Http_Request'Class (Http.Delegate.all).Timeouts := AWS.Client.Timeouts (Connect => Timeout, Send => Timeout, Receive => Timeout, Response => Timeout); end Set_Timeout; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Put; overriding procedure Do_Delete (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Delete {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in AWS_Http_Manager; Http : in Client'Class; Timeout : in Duration) is begin AWS_Http_Request'Class (Http.Delegate.all).Timeouts := AWS.Client.Timeouts (Connect => Timeout, Send => Timeout, Receive => Timeout, Response => Timeout); end Set_Timeout; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
Implement the Do_Delete procedure for AWS
Implement the Do_Delete procedure for AWS
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
940d8826e009fecf8d066dd74753402727fae0e9
awa/samples/src/atlas-reviews-beans.ads
awa/samples/src/atlas-reviews-beans.ads
----------------------------------------------------------------------- -- atlas-reviews-beans -- Beans for module reviews -- 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 Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Atlas.Reviews.Modules; with Atlas.Reviews.Models; package Atlas.Reviews.Beans is type Review_Bean is new Atlas.Reviews.Models.Review_Bean with record Module : Atlas.Reviews.Modules.Review_Module_Access := null; end record; type Review_Bean_Access is access all Review_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Review_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Review_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Save (Bean : in out Review_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Delete (Bean : in out Review_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Reviews_Bean bean instance. function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end Atlas.Reviews.Beans;
----------------------------------------------------------------------- -- atlas-reviews-beans -- Beans for module reviews -- 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 Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Atlas.Reviews.Modules; with Atlas.Reviews.Models; package Atlas.Reviews.Beans is type Review_Bean is new Atlas.Reviews.Models.Review_Bean with record Module : Atlas.Reviews.Modules.Review_Module_Access := null; end record; type Review_Bean_Access is access all Review_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Review_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Review_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Save (Bean : in out Review_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Delete (Bean : in out Review_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Load (Bean : in out Review_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Reviews_Bean bean instance. function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Review_List_Bean is new Atlas.Reviews.Models.Review_List_Bean with record Module : Atlas.Reviews.Modules.Review_Module_Access := null; Reviews : aliased Atlas.Reviews.Models.List_Info_List_Bean; Reviews_Bean : Atlas.Reviews.Models.List_Info_List_Bean_Access; end record; type Review_List_Bean_Access is access all Review_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Review_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Review_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Review_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Review_List_Bean bean instance. function Create_Review_List_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end Atlas.Reviews.Beans;
Define the Review_List_Bean type
Define the Review_List_Bean type
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
493895387506efa97b876ff559f79c8dacaa23b9
mat/regtests/mat-frames-tests.adb
mat/regtests/mat-frames-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Test_Caller; with MAT.Frames.Print; with MAT.Readers.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; end MAT.Frames.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Test_Caller; with MAT.Frames.Print; with MAT.Readers.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Release", Test_Release_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; -- ------------------------------ -- Test allocating and releasing frames. -- ------------------------------ procedure Test_Release_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F1 : Frame_Type; F2 : Frame_Type; F3 : Frame_Type; begin Insert (Root, Frame_1_1, F1); T.Assert (Root.Used > 0, "Insert must increment the root used count"); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_2, F2); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_3, F3); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Output, "Release frame F1"); Release (F1); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); T.Assert (F2.Used > 0, "Release must not change other frames"); T.Assert (Root.Used > 0, "Release must not change root frame"); Destroy (Root); end Test_Release_Frames; end MAT.Frames.Tests;
Implement the Test_Release_Frames procedure
Implement the Test_Release_Frames procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
40ea4ae252ac45a32f4637e14844cffba0e9f5bc
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Systems.Os; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)", Test_Input_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test input file redirection. -- ------------------------------ procedure Test_Input_Redirect (T : in out Test) is P : Process; In_Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/proc-input.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/proc-inres.txt"); Exp_Path : constant String := Util.Tests.Get_Test_Path ("regtests/expect/proc-inres.txt"); begin Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Spawn (P, "bin/util_test_process 0 read -"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Input_Redirect; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
Implement Test_Input_Redirect and register the new test for execution
Implement Test_Input_Redirect and register the new test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7afa026faab240c8972829362098b2d8de62cbc1
awa/src/awa-events-dispatchers-tasks.ads
awa/src/awa-events-dispatchers-tasks.ads
----------------------------------------------------------------------- -- awa-events-dispatchers-tasks -- AWA Event Dispatchers -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Concurrent.Fifos; with AWA.Events.Queues; with AWA.Events.Services; package AWA.Events.Dispatchers.Tasks is type Task_Dispatcher is limited new Dispatcher with private; type Task_Dispatcher_Access is access all Task_Dispatcher; -- Start the dispatcher. overriding procedure Start (Manager : in out Task_Dispatcher); -- Stop the dispatcher. overriding procedure Stop (Manager : in out Task_Dispatcher); -- Add the queue to the dispatcher. overriding procedure Add_Queue (Manager : in out Task_Dispatcher; Queue : in AWA.Events.Queues.Queue_Ref; Added : out Boolean); overriding procedure Finalize (Object : in out Task_Dispatcher) renames Stop; function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; Match : in String; Count : in Positive; Priority : in Positive) return Dispatcher_Access; private package Queue_Of_Queue is new Util.Concurrent.Fifos (Element_Type => AWA.Events.Queues.Queue_Ref, Default_Size => 10, Clear_On_Dequeue => True); task type Consumer is entry Start (D : in Task_Dispatcher_Access); entry Stop; end Consumer; type Consumer_Array is array (Positive range <>) of Consumer; type Consumer_Array_Access is access Consumer_Array; type Task_Dispatcher is limited new Dispatcher with record Workers : Consumer_Array_Access; Queues : Queue_Of_Queue.Fifo; Task_Count : Positive; Match : Ada.Strings.Unbounded.Unbounded_String; Priority : Positive; end record; end AWA.Events.Dispatchers.Tasks;
----------------------------------------------------------------------- -- awa-events-dispatchers-tasks -- AWA Event Dispatchers -- Copyright (C) 2012, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Concurrent.Fifos; with AWA.Events.Queues; with AWA.Events.Services; with AWA.Events.Queues.Observers; package AWA.Events.Dispatchers.Tasks is subtype Observer is Queues.Observers.Observer; type Task_Dispatcher is limited new Dispatcher and Observer with private; type Task_Dispatcher_Access is access all Task_Dispatcher; -- Start the dispatcher. overriding procedure Start (Manager : in out Task_Dispatcher); -- Stop the dispatcher. overriding procedure Stop (Manager : in out Task_Dispatcher); -- Add the queue to the dispatcher. overriding procedure Add_Queue (Manager : in out Task_Dispatcher; Queue : in AWA.Events.Queues.Queue_Ref; Added : out Boolean); -- Inform the dispatch that some events may have been queued. overriding procedure Update (Manager : in Task_Dispatcher; Queue : in Queues.Queue_Ref); overriding procedure Finalize (Object : in out Task_Dispatcher) renames Stop; function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; Match : in String; Count : in Positive; Priority : in Positive) return Dispatcher_Access; private package Queue_Of_Queue is new Util.Concurrent.Fifos (Element_Type => AWA.Events.Queues.Queue_Ref, Default_Size => 10, Clear_On_Dequeue => True); task type Consumer is entry Start (D : in Task_Dispatcher_Access); entry Stop; entry Wakeup; end Consumer; type Consumer_Array is array (Positive range <>) of Consumer; type Consumer_Array_Access is access Consumer_Array; type Task_Dispatcher is limited new Dispatcher and Observer with record Workers : Consumer_Array_Access; Queues : Queue_Of_Queue.Fifo; Task_Count : Positive; Match : Ada.Strings.Unbounded.Unbounded_String; Priority : Positive; end record; end AWA.Events.Dispatchers.Tasks;
Implement the event queue Observer interface with the Update operation
Implement the event queue Observer interface with the Update operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
69373dae0f58adb775f2e57cbcf678cfd973bce4
regtests/systems/util-systems-os-tests.ads
regtests/systems/util-systems-os-tests.ads
----------------------------------------------------------------------- -- util-systems-os-tests -- Unit tests for OS specific operations -- 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.Tests; package Util.Systems.OS.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Sys_Stat operation. procedure Test_Stat (T : in out Test); -- Test the Sys_Stat operation on a directory. procedure Test_Stat_Directory (T : in out Test); end Util.Systems.OS.Tests;
----------------------------------------------------------------------- -- util-systems-os-tests -- Unit tests for OS specific operations -- Copyright (C) 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Systems.Os.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Sys_Stat operation. procedure Test_Stat (T : in out Test); -- Test the Sys_Stat operation on a directory. procedure Test_Stat_Directory (T : in out Test); end Util.Systems.Os.Tests;
Fix style warning
Fix style warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
39746e33d978733dd7645ffe2e74b5b1ea6fa25e
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Readers.Streams.Sockets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Readers.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Readers.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Events.Probes; with MAT.Readers; with MAT.Readers.Streams; with MAT.Readers.Streams.Sockets; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is received. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Print the events as they are received. Print_Events : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. overriding procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled and MAT.Events.Probes.Reader_List_Type with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
Use the MAT.Events.Probes package
Use the MAT.Events.Probes package
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b7ce562f95f3c8e6053bafdac24681874d52213f
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- == Step 1: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- associate with us and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Step 2: verify the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- == Step 1: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Step 2: verify the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
Document the OpenID process
Document the OpenID process
Ada
apache-2.0
stcarrez/ada-security
5183b822852f44246f32945454bbd3618fe91545
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Concurrent.Counters; with Util.Beans.Objects; with Util.Beans.Basic; private with Util.Beans.Objects.Maps; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Insert the specified property in the list. procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array; -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract tagged limited record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; type Manager_Factory is access function return Manager_Access; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean is abstract; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value is abstract; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is abstract; -- 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 abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; procedure Delete (Self : in Manager; Obj : in out Manager_Access) is abstract; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is abstract; end Interface_P; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access); -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; private with Util.Concurrent.Counters; private with Util.Beans.Objects.Maps; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array; -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; type Manager_Factory is access function return Manager_Access; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; procedure Delete (Self : in Manager; Obj : in out Manager_Access) is abstract; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is abstract; end Interface_P; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access); -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Refactor (step 1) for Properties package: - Remove the Insert procedure which is similar to Set - Internal type Manager implements the Bean interface
Refactor (step 1) for Properties package: - Remove the Insert procedure which is similar to Set - Internal type Manager implements the Bean interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
374a9c939aa9121df4ba894782c563a2684d44c5
regtests/el-testsuite.adb
regtests/el-testsuite.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 EL.Expressions; with EL.Objects; with EL.Objects.Enums; with EL.Objects.Time; with EL.Contexts; with EL.Contexts.Default; with Ada.Calendar; with EL.Objects.Discrete_Tests; with EL.Objects.Time.Tests; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; with Interfaces.C; with EL.Expressions.Tests; package body EL.Testsuite is use Interfaces.C; use EL.Objects; use Ada.Calendar; use Ada.Calendar.Conversions; function "+" (Left, Right : Boolean) return Boolean; function "-" (Left, Right : Boolean) return Boolean; function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time; function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time; function Time_Value (S : String) return Ada.Calendar.Time; -- ------------------------------ -- 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 Test_Integer is new EL.Objects.Discrete_Tests (Test_Type => Integer, To_Type => EL.Objects.To_Integer, To_Object_Test => EL.Objects.To_Object, Value => Integer'Value, Test_Name => "Integer", Test_Values => "-100,1,0,1,1000"); package Test_Long_Integer is new EL.Objects.Discrete_Tests (Test_Type => Long_Integer, To_Type => EL.Objects.To_Long_Integer, To_Object_Test => EL.Objects.To_Object, Value => Long_Integer'Value, Test_Name => "Long_Integer", Test_Values => "-100,1,0,1,1000"); package Test_Long_Long_Integer is new EL.Objects.Discrete_Tests (Test_Type => Long_Long_Integer, To_Type => EL.Objects.To_Long_Long_Integer, To_Object_Test => EL.Objects.To_Object, Value => Long_Long_Integer'Value, Test_Name => "Long_Long_Integer", Test_Values => "-10000000000000,1,0,1,1000_000_000_000"); function "-" (Left, Right : Boolean) return Boolean is begin return Left and Right; end "-"; function "+" (Left, Right : Boolean) return Boolean is begin return Left or Right; end "+"; package Test_Boolean is new EL.Objects.Discrete_Tests (Test_Type => Boolean, To_Type => EL.Objects.To_Boolean, To_Object_Test => EL.Objects.To_Object, Value => Boolean'Value, Test_Name => "Boolean", Test_Values => "false,true"); type Color is (WHITE, BLACK, RED, GREEN, BLUE, YELLOW); package Color_Object is new EL.Objects.Enums (Color, ROUND_VALUE => True); function "-" (Left, Right : Color) return Color is N : constant Integer := Color'Pos (Left) - Color'Pos (Right); begin if N >= 0 then return Color'Val ((Color'Pos (WHITE) + N) mod 6); else return Color'Val ((Color'Pos (WHITE) - N) mod 6); end if; end "-"; function "+" (Left, Right : Color) return Color is N : constant Integer := Color'Pos (Left) + Color'Pos (Right); begin return Color'Val ((Color'Pos (WHITE) + N) mod 6); end "+"; package Test_Enum is new EL.Objects.Discrete_Tests (Test_Type => Color, To_Type => Color_Object.To_Value, To_Object_Test => Color_Object.To_Object, Value => Color'Value, Test_Name => "Color", Test_Values => "BLACK,RED,GREEN,BLUE,YELLOW"); Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); function Time_Value (S : String) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Value (S); end Time_Value; function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is T1 : constant Duration := Left - Epoch; T2 : constant Duration := Right - Epoch; begin return (T1 + T2) + Epoch; end "+"; function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is T1 : constant Duration := Left - Epoch; T2 : constant Duration := Right - Epoch; begin return (T1 - T2) + Epoch; end "-"; package Test_Time is new EL.Objects.Discrete_Tests (Test_Type => Ada.Calendar.Time, To_Type => EL.Objects.Time.To_Time, To_Object_Test => EL.Objects.Time.To_Object, Value => Time_Value, Test_Name => "Time", Test_Values => "1970-03-04 12:12:00,1975-05-04 13:13:10"); package Test_Float is new EL.Objects.Discrete_Tests (Test_Type => Float, To_Type => EL.Objects.To_Float, To_Object_Test => EL.Objects.To_Object, Value => Float'Value, Test_Name => "Float", Test_Values => "1.2,3.3,-3.3"); package Test_Long_Float is new EL.Objects.Discrete_Tests (Test_Type => Long_Float, To_Type => EL.Objects.To_Long_Float, To_Object_Test => EL.Objects.To_Object, Value => Long_Float'Value, Test_Name => "Long_Float", Test_Values => "1.2,3.3,-3.3"); package Test_Long_Long_Float is new EL.Objects.Discrete_Tests (Test_Type => Long_Long_Float, To_Type => EL.Objects.To_Long_Long_Float, To_Object_Test => EL.Objects.To_Object, Value => Long_Long_Float'Value, Test_Name => "Long_Long_Float", Test_Values => "1.2,3.3,-3.3"); package Caller is new AUnit.Test_Caller (Test); Tests : aliased Test_Suite; function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := Tests'Access; begin Ret.Add_Test (Caller.Create ("Test To_Object (Integer)", Test_To_Object_Integer'Access)); Ret.Add_Test (Caller.Create ("Test Expressions", Test_Expression'Access)); Test_Boolean.Add_Tests (Ret); Test_Integer.Add_Tests (Ret); Test_Long_Integer.Add_Tests (Ret); Test_Long_Long_Integer.Add_Tests (Ret); Test_Time.Add_Tests (Ret); Test_Float.Add_Tests (Ret); Test_Long_Float.Add_Tests (Ret); Test_Long_Long_Float.Add_Tests (Ret); Test_Enum.Add_Tests (Ret); EL.Objects.Time.Tests.Add_Tests (Ret); EL.Expressions.Tests.Add_Tests (Ret); return Ret; end Suite; end EL.Testsuite;
----------------------------------------------------------------------- -- 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 EL.Expressions; with EL.Objects; with EL.Objects.Enums; with EL.Objects.Time; with EL.Contexts; with EL.Contexts.Default; with Ada.Calendar; with EL.Objects.Discrete_Tests; with EL.Objects.Time.Tests; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; with Interfaces.C; with EL.Expressions.Tests; package body EL.Testsuite is use Interfaces.C; use EL.Objects; use Ada.Calendar; use Ada.Calendar.Conversions; function "+" (Left, Right : Boolean) return Boolean; function "-" (Left, Right : Boolean) return Boolean; function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time; function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time; function Time_Value (S : String) return Ada.Calendar.Time; -- ------------------------------ -- 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 Test_Integer is new EL.Objects.Discrete_Tests (Test_Type => Integer, To_Type => EL.Objects.To_Integer, To_Object_Test => EL.Objects.To_Object, Value => Integer'Value, Test_Name => "Integer", Test_Values => "-100,1,0,1,1000"); package Test_Long_Integer is new EL.Objects.Discrete_Tests (Test_Type => Long_Integer, To_Type => EL.Objects.To_Long_Integer, To_Object_Test => EL.Objects.To_Object, Value => Long_Integer'Value, Test_Name => "Long_Integer", Test_Values => "-100,1,0,1,1000"); package Test_Long_Long_Integer is new EL.Objects.Discrete_Tests (Test_Type => Long_Long_Integer, To_Type => EL.Objects.To_Long_Long_Integer, To_Object_Test => EL.Objects.To_Object, Value => Long_Long_Integer'Value, Test_Name => "Long_Long_Integer", Test_Values => "-10000000000000,1,0,1,1000_000_000_000"); function "-" (Left, Right : Boolean) return Boolean is begin return Left and Right; end "-"; function "+" (Left, Right : Boolean) return Boolean is begin return Left or Right; end "+"; package Test_Boolean is new EL.Objects.Discrete_Tests (Test_Type => Boolean, To_Type => EL.Objects.To_Boolean, To_Object_Test => EL.Objects.To_Object, Value => Boolean'Value, Test_Name => "Boolean", Test_Values => "false,true"); type Color is (WHITE, BLACK, RED, GREEN, BLUE, YELLOW); package Color_Object is new EL.Objects.Enums (Color, ROUND_VALUE => True); function "-" (Left, Right : Color) return Color is N : constant Integer := Color'Pos (Left) - Color'Pos (Right); begin if N >= 0 then return Color'Val ((Color'Pos (WHITE) + N) mod 6); else return Color'Val ((Color'Pos (WHITE) - N) mod 6); end if; end "-"; function "+" (Left, Right : Color) return Color is N : constant Integer := Color'Pos (Left) + Color'Pos (Right); begin return Color'Val ((Color'Pos (WHITE) + N) mod 6); end "+"; package Test_Enum is new EL.Objects.Discrete_Tests (Test_Type => Color, To_Type => Color_Object.To_Value, To_Object_Test => Color_Object.To_Object, Value => Color'Value, Test_Name => "Color", Test_Values => "BLACK,RED,GREEN,BLUE,YELLOW"); Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); function Time_Value (S : String) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Value (S); end Time_Value; -- For the purpose of the time unit test, we need Time + Time operation even -- if this does not really makes sense. function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is T1 : constant Duration := Left - Epoch; T2 : constant Duration := Right - Epoch; begin return (T1 + T2) + Epoch; end "+"; function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is T1 : constant Duration := Left - Epoch; T2 : constant Duration := Right - Epoch; begin return (T1 - T2) + Epoch; end "-"; package Test_Time is new EL.Objects.Discrete_Tests (Test_Type => Ada.Calendar.Time, To_Type => EL.Objects.Time.To_Time, To_Object_Test => EL.Objects.Time.To_Object, Value => Time_Value, Test_Name => "Time", Test_Values => "1970-03-04 12:12:00,1975-05-04 13:13:10"); package Test_Float is new EL.Objects.Discrete_Tests (Test_Type => Float, To_Type => EL.Objects.To_Float, To_Object_Test => EL.Objects.To_Object, Value => Float'Value, Test_Name => "Float", Test_Values => "1.2,3.3,-3.3"); package Test_Long_Float is new EL.Objects.Discrete_Tests (Test_Type => Long_Float, To_Type => EL.Objects.To_Long_Float, To_Object_Test => EL.Objects.To_Object, Value => Long_Float'Value, Test_Name => "Long_Float", Test_Values => "1.2,3.3,-3.3"); package Test_Long_Long_Float is new EL.Objects.Discrete_Tests (Test_Type => Long_Long_Float, To_Type => EL.Objects.To_Long_Long_Float, To_Object_Test => EL.Objects.To_Object, Value => Long_Long_Float'Value, Test_Name => "Long_Long_Float", Test_Values => "1.2,3.3,-3.3"); package Caller is new AUnit.Test_Caller (Test); Tests : aliased Test_Suite; function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := Tests'Access; begin Ret.Add_Test (Caller.Create ("Test To_Object (Integer)", Test_To_Object_Integer'Access)); Ret.Add_Test (Caller.Create ("Test Expressions", Test_Expression'Access)); Test_Boolean.Add_Tests (Ret); Test_Integer.Add_Tests (Ret); Test_Long_Integer.Add_Tests (Ret); Test_Long_Long_Integer.Add_Tests (Ret); Test_Time.Add_Tests (Ret); Test_Float.Add_Tests (Ret); Test_Long_Float.Add_Tests (Ret); Test_Long_Long_Float.Add_Tests (Ret); Test_Enum.Add_Tests (Ret); EL.Objects.Time.Tests.Add_Tests (Ret); EL.Expressions.Tests.Add_Tests (Ret); return Ret; end Suite; end EL.Testsuite;
Add comment
Add comment
Ada
apache-2.0
stcarrez/ada-el
3f90c4cc50b1ce81f8bc977a010e15419a24e364
src/wiki-html_parser.ads
src/wiki-html_parser.ads
----------------------------------------------------------------------- -- wiki-html_parser -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Attributes; -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the `Parse_Element` and it calls back the `Process` -- parameter procedure with the element name and the optional attributes. private package Wiki.Html_Parser is pragma Preelaborate; type State_Type is (HTML_START, HTML_END, HTML_START_END, HTML_ERROR); type Entity_State_Type is (ENTITY_NONE, ENTITY_MIDDLE, ENTITY_VALID); type Parser_Type is limited private; function Is_Empty (Parser : in Parser_Type) return Boolean; -- Parse a HTML element `<XXX attributes>` or parse an end of HTML element </XXX> -- The first '<' is assumed to have been already verified. procedure Parse_Element (Parser : in out Parser_Type; Text : in Wiki.Strings.WString; From : in Positive; Process : not null access procedure (Kind : in State_Type; Name : in Wiki.Strings.WString; Attr : in out Wiki.Attributes.Attribute_List); Last : out Positive); -- Parse an HTML entity such as `&nbsp;` and return its value with the last position -- if it was correct. The first `&` is assumed to have been already verified. -- When `Entity` is not 0, the parsing is finished. When `Last` exceeds the input -- text position, it is necessary to call `Parse_Entity` with the next input chunk. procedure Parse_Entity (Parser : in out Parser_Type; Text : in Wiki.Strings.WString; From : in Positive; Status : in out Entity_State_Type; Entity : out Wiki.Strings.WChar; Last : out Natural); NUL : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (0); private type Html_Parser_State is (State_None, State_Comment_Or_Doctype, State_Doctype, State_Comment, State_Element, State_Check_Attribute, State_Parse_Attribute, State_Check_Attribute_Value, State_Parse_Attribute_Value, State_Valid_Attribute_Value, State_No_Attribute_Value, State_Expect_Start_End_Element, State_Expect_End_Element, State_End_Element); MAX_ENTITY_LENGTH : constant := 10; type Parser_Type is limited record State : Html_Parser_State := State_None; Elt_Name : Wiki.Strings.BString (64); Attr_Name : Wiki.Strings.BString (64); Attr_Value : Wiki.Strings.BString (256); Attributes : Wiki.Attributes.Attribute_List; Entity_Name : String (1 .. MAX_ENTITY_LENGTH); Counter : Natural := 0; Separator : Wiki.Strings.WChar; end record; end Wiki.Html_Parser;
----------------------------------------------------------------------- -- wiki-html_parser -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Attributes; -- This is a small HTML parser that is called to deal with embedded HTML in wiki text. -- The parser is intended to handle incorrect HTML and clean the result as much as possible. -- We cannot use a real XML/Sax parser (such as XML/Ada) because we must handle errors and -- backtrack from HTML parsing to wiki or raw text parsing. -- -- When parsing HTML content, we call the `Parse_Element` and it calls back the `Process` -- parameter procedure with the element name and the optional attributes. private package Wiki.Html_Parser is pragma Preelaborate; type State_Type is (HTML_START, HTML_END, HTML_START_END, HTML_ERROR); type Entity_State_Type is (ENTITY_NONE, ENTITY_MIDDLE, ENTITY_VALID); type Parser_Type is limited private; function Is_Empty (Parser : in Parser_Type) return Boolean; -- Parse a HTML element `<XXX attributes>` or parse an end of HTML element </XXX> -- The first '<' is assumed to have been already verified. procedure Parse_Element (Parser : in out Parser_Type; Text : in Wiki.Strings.WString; From : in Positive; Process : not null access procedure (Kind : in State_Type; Name : in Wiki.Strings.WString; Attr : in out Wiki.Attributes.Attribute_List); Last : out Positive); -- Parse an HTML entity such as `&nbsp;` and return its value with the last position -- if it was correct. The first `&` is assumed to have been already verified. -- When `Entity` is not 0, the parsing is finished. When `Last` exceeds the input -- text position, it is necessary to call `Parse_Entity` with the next input chunk. procedure Parse_Entity (Parser : in out Parser_Type; Text : in Wiki.Strings.WString; From : in Positive; Status : in out Entity_State_Type; Entity : out Wiki.Strings.WChar; Last : out Natural); NUL : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (0); private type Html_Parser_State is (State_None, State_Comment_Or_Doctype, State_Doctype, State_Comment, State_Element, State_Check_Attribute, State_Parse_Attribute, State_Check_Attribute_Value, State_Parse_Attribute_Value, State_Valid_Attribute_Value, State_No_Attribute_Value, State_Expect_Start_End_Element, State_Expect_End_Element, State_End_Element); MAX_ENTITY_LENGTH : constant := 32; type Parser_Type is limited record State : Html_Parser_State := State_None; Elt_Name : Wiki.Strings.BString (64); Attr_Name : Wiki.Strings.BString (64); Attr_Value : Wiki.Strings.BString (256); Attributes : Wiki.Attributes.Attribute_List; Entity_Name : String (1 .. MAX_ENTITY_LENGTH); Counter : Natural := 0; Separator : Wiki.Strings.WChar; end record; end Wiki.Html_Parser;
Change MAX_ENTITY_LENGTH to 32 because the HTML5 defines a very long entity name
Change MAX_ENTITY_LENGTH to 32 because the HTML5 defines a very long entity name
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b2894ce13caa6b93c9c9bbc4539c8222dd464552
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Need_Newline : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Need_Newline : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Add Empty_Previous_Line in the Wiki_Renderer type
Add Empty_Previous_Line in the Wiki_Renderer type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
701490f91895c9a148b6c30b11c849d066253823
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; 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; -- 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; -- 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) 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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 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; -- 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 result directory path. function Get_Result_Directory (Handler : in Generator) return String 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) 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;
Add the Get_Result_Directory function to the Artifact interface
Add the Get_Result_Directory function to the Artifact interface
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
015c336444358f3f60b3ff6510fa97692f39a06c
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. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private 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 := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_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 := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Declare the Permission_Role_Array type Add a Grants member to the Role_Policy type to know easily the roles that grant a given permission
Declare the Permission_Role_Array type Add a Grants member to the Role_Policy type to know easily the roles that grant a given permission
Ada
apache-2.0
stcarrez/ada-security
35b2a942da811625f1005318f5c2b7c8e3b8760d
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. 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;
----------------------------------------------------------------------- -- 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; -- ------------------------------ -- 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;
Remove Permission_Type and Permission_Map
Remove Permission_Type and Permission_Map
Ada
apache-2.0
stcarrez/ada-security
1b3e103f6dfaaf2776dcd0bbc13ab8f5777bd8a9
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; 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; -- 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 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; -- 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) 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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 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; -- 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; -- 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) 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;
Add the Get_Config_Directory function to the artifact interface
Add the Get_Config_Directory function to the artifact interface
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
363bb87a6a0c9bd0b506b811435e23c24f25dc31
src/security-auth.ads
src/security-auth.ads
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 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.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- = Authentication = -- The `Security.Auth` package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- https://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Core 1.0 -- https://openid.net/specs/openid-connect-core-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by `Security.Auth` defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * `Discovery`: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * `Verify`: to decode the authentication and check its result. -- -- [[images/OpenID.png]] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The `Verify` procedure is called with the association to check the result and -- obtain the authentication results. -- -- == Initialization == -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth-googleplus.ads -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- == Principal creation == -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; -- Use the Google+ OpenID Connect Basic Client PROVIDER_GOOGLE_PLUS : constant String := "google-plus"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- = Authentication = -- The `Security.Auth` package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- https://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Core 1.0 -- https://openid.net/specs/openid-connect-core-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by `Security.Auth` defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * `Discovery`: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * `Verify`: to decode the authentication and check its result. -- -- [[images/OpenID.png]] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The `Verify` procedure is called with the association to check the result and -- obtain the authentication results. -- -- == Initialization == -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth-googleplus.ads -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- == Principal creation == -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; -- Use the Google+ OpenID Connect Basic Client PROVIDER_GOOGLE_PLUS : constant String := "google-plus"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; type Manager_Access is access all Manager'Class; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Factory : not null access function (Name : in String) return Manager_Access; Name : in String := PROVIDER_OPENID); -- Discover the authentication provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Default factory used by `Initialize`. It supports OpenID, Google, Facebook. function Default_Factory (Provider : in String) return Manager_Access; private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
Declare Default_Factory and add a new Initialize procedure with a factory parameter
Declare Default_Factory and add a new Initialize procedure with a factory parameter
Ada
apache-2.0
stcarrez/ada-security
42bab4e62627dd042c55bc78d2126667458bf247
src/security-random.adb
src/security-random.adb
----------------------------------------------------------------------- -- security-random -- Random numbers for nonce, secret keys, token generation -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Ada.Calendar; with Ada.Calendar.Conversions; with Util.Encoders.Base64; package body Security.Random is use Interfaces; -- ------------------------------ -- Initialize the random generator. -- ------------------------------ overriding procedure Initialize (Gen : in out Generator) is begin Gen.Rand.Reset; end Initialize; -- ------------------------------ -- Fill the array with pseudo-random numbers. -- ------------------------------ procedure Generate (Gen : in out Generator; Into : out Ada.Streams.Stream_Element_Array) is begin Gen.Rand.Generate (Into); end Generate; -- ------------------------------ -- Generate a random sequence of bits and convert the result -- into a string in base64url. -- ------------------------------ function Generate (Gen : in out Generator'Class; Bits : in Positive) return String is use type Ada.Streams.Stream_Element_Offset; Rand_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32)); Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1); Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3); Encoder : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin -- Generate the random sequence. Gen.Generate (Rand); -- Encode the random stream in base64url and save it into the result string. Encoder.Set_URL_Mode (True); Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); declare Result : String (1 .. Natural (Encoded + 1)); begin for I in 0 .. Encoded loop Result (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; return Result; end; end Generate; -- ------------------------------ -- Generate a random sequence of bits, convert the result -- into a string in base64url and append it to the buffer. -- ------------------------------ procedure Generate (Gen : in out Generator'Class; Bits : in Positive; Into : in out Ada.Strings.Unbounded.Unbounded_String) is use type Ada.Streams.Stream_Element_Offset; Rand_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32)); Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1); Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3); Encoder : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin -- Generate the random sequence. Gen.Generate (Rand); -- Encode the random stream in base64url and save it into the result string. Encoder.Set_URL_Mode (True); Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); for I in 0 .. Encoded loop Ada.Strings.Unbounded.Append (Into, Character'Val (Buffer (I))); end loop; end Generate; -- Protected type to allow using the random generator by several tasks. protected body Raw_Generator is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; Size : constant Ada.Streams.Stream_Element_Offset := Into'Length / 4; Remain : constant Ada.Streams.Stream_Element_Offset := Into'Length mod 4; Value : Unsigned_32; begin -- Generate the random sequence (fill 32-bits at a time for each random call). for I in 0 .. Size - 1 loop Value := Id_Random.Random (Rand); Into (Into'First + 4 * I) := Stream_Element (Value and 16#0FF#); Into (Into'First + 4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (Into'First + 4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (Into'First + 4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end loop; -- Fill the remaining bytes. if Remain > 0 then Value := Id_Random.Random (Rand); for I in 0 .. Remain - 1 loop Into (Into'Last - I) := Stream_Element (Value and 16#0FF#); Value := Shift_Right (Value, 8); end loop; end if; end Generate; procedure Reset is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; S : constant Ada.Calendar.Day_Duration := Ada.Calendar.Seconds (Now); Sec : Interfaces.C.long; Nsec : Interfaces.C.long; begin Ada.Calendar.Conversions.To_Struct_Timespec (S, Sec, Nsec); Id_Random.Reset (Rand, Integer (Unsigned_32 (Sec) xor Unsigned_32 (Nsec))); end Reset; end Raw_Generator; end Security.Random;
----------------------------------------------------------------------- -- security-random -- Random numbers for nonce, secret keys, token generation -- Copyright (C) 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Ada.Calendar; with Ada.Calendar.Conversions; with Util.Encoders.Base64; package body Security.Random is use Interfaces; -- ------------------------------ -- Initialize the random generator. -- ------------------------------ overriding procedure Initialize (Gen : in out Generator) is begin Gen.Rand.Reset; end Initialize; -- ------------------------------ -- Fill the array with pseudo-random numbers. -- ------------------------------ procedure Generate (Gen : in out Generator; Into : out Ada.Streams.Stream_Element_Array) is begin Gen.Rand.Generate (Into); end Generate; -- ------------------------------ -- Generate a random sequence of bits and convert the result -- into a string in base64url. -- ------------------------------ function Generate (Gen : in out Generator'Class; Bits : in Positive) return String is use type Ada.Streams.Stream_Element_Offset; Rand_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32)); Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1); Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3); Encoder : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin -- Generate the random sequence. Gen.Generate (Rand); -- Encode the random stream in base64url and save it into the result string. Encoder.Set_URL_Mode (True); Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Encoder.Finish (Into => Buffer (Last + 1 .. Buffer'Last), Last => Last); while Character'Val (Buffer (Last)) = '=' loop Last := Last - 1; end loop; declare Result : String (1 .. Natural (Last + 1)); begin for I in 0 .. Last loop Result (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; return Result; end; end Generate; -- ------------------------------ -- Generate a random sequence of bits, convert the result -- into a string in base64url and append it to the buffer. -- ------------------------------ procedure Generate (Gen : in out Generator'Class; Bits : in Positive; Into : in out Ada.Strings.Unbounded.Unbounded_String) is use type Ada.Streams.Stream_Element_Offset; Rand_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32)); Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1); Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3); Encoder : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin -- Generate the random sequence. Gen.Generate (Rand); -- Encode the random stream in base64url and save it into the result string. Encoder.Set_URL_Mode (True); Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Encoder.Finish (Into => Buffer (Last + 1 .. Buffer'Last), Last => Last); while Character'Val (Buffer (Last)) = '=' loop Last := Last - 1; end loop; for I in 0 .. Last loop Ada.Strings.Unbounded.Append (Into, Character'Val (Buffer (I))); end loop; end Generate; -- Protected type to allow using the random generator by several tasks. protected body Raw_Generator is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; Size : constant Ada.Streams.Stream_Element_Offset := Into'Length / 4; Remain : constant Ada.Streams.Stream_Element_Offset := Into'Length mod 4; Value : Unsigned_32; begin -- Generate the random sequence (fill 32-bits at a time for each random call). for I in 0 .. Size - 1 loop Value := Id_Random.Random (Rand); Into (Into'First + 4 * I) := Stream_Element (Value and 16#0FF#); Into (Into'First + 4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (Into'First + 4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (Into'First + 4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end loop; -- Fill the remaining bytes. if Remain > 0 then Value := Id_Random.Random (Rand); for I in 0 .. Remain - 1 loop Into (Into'Last - I) := Stream_Element (Value and 16#0FF#); Value := Shift_Right (Value, 8); end loop; end if; end Generate; procedure Reset is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; S : constant Ada.Calendar.Day_Duration := Ada.Calendar.Seconds (Now); Sec : Interfaces.C.long; Nsec : Interfaces.C.long; begin Ada.Calendar.Conversions.To_Struct_Timespec (S, Sec, Nsec); Id_Random.Reset (Rand, Integer (Unsigned_32 (Sec) xor Unsigned_32 (Nsec))); end Reset; end Raw_Generator; end Security.Random;
Fix conversion of random bits in base64 which was dropping the last bytes (the random string was shorter than expected)
Fix conversion of random bits in base64 which was dropping the last bytes (the random string was shorter than expected)
Ada
apache-2.0
stcarrez/ada-security
31777c25a2987bf32e517189cdb4428b308e01fc
regtests/ado-objects-tests.adb
regtests/ado-objects-tests.adb
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); end Add_Tests; end ADO.Objects.Tests;
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); end Add_Tests; end ADO.Objects.Tests;
Add a test for Is_Loaded function
Add a test for Is_Loaded function
Ada
apache-2.0
stcarrez/ada-ado
18f5a9db31cc8fcb06ba376184989f01357c5093
awa/plugins/awa-storages/src/awa-storages-services.ads
awa/plugins/awa-storages/src/awa-storages-services.ads
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : in out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : in out AWA.Storages.Storage_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : in out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : in out AWA.Storages.Storage_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); -- Publish or not the storage instance. procedure Publish (Service : in Storage_Service; Id : in ADO.Identifier; State : in Boolean; File : in out AWA.Storages.Models.Storage_Ref'Class); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
Declare the Publish operation to change the pulication status of the document
Declare the Publish operation to change the pulication status of the document
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a05cbf937c8e01ad914d732ded15ee582db932ce
src/base/beans/util-beans-objects-time.adb
src/base/beans/util-beans-objects-time.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010, 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 Interfaces.C; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; package body Util.Beans.Objects.Time is use Ada.Calendar; Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); -- ------------------------------ -- Time Type -- ------------------------------ type Time_Type_Def is new Duration_Type_Def with null record; -- Get the type name function Get_Name (Type_Def : Time_Type_Def) return String; -- Convert the value into a string. function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String; Time_Type : aliased constant Time_Type_Def := Time_Type_Def '(null record); -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Time_Type_Def) return String is pragma Unreferenced (Type_Def); begin return "Time"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Ada.Calendar.Formatting.Image (Epoch + Value.Time_Value); end To_String; -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in Ada.Calendar.Time) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value - Epoch), Type_Def => Time_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Time (Value : in Object) return Ada.Calendar.Time is begin case Value.V.Of_Type is when TYPE_TIME => return Value.V.Time_Value + Epoch; when TYPE_STRING | TYPE_WIDE_STRING => declare T : constant String := Value.Type_Def.To_String (Value.V); begin return Ada.Calendar.Formatting.Value (T); exception -- Last chance, try to convert a Unix time displayed as an integer. when Constraint_Error => return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (T)); end; when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end To_Time; -- ------------------------------ -- Force the object to be a time. -- ------------------------------ function Cast_Time (Value : Object) return Object is begin case Value.V.Of_Type is when TYPE_TIME => return Value; when TYPE_STRING | TYPE_WIDE_STRING => return Time.To_Object (Formatting.Value (Value.Type_Def.To_String (Value.V))); when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end Cast_Time; end Util.Beans.Objects.Time;
----------------------------------------------------------------------- -- util-beans-objects-time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010, 2013, 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 Interfaces.C; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; package body Util.Beans.Objects.Time is use Ada.Calendar; Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); -- ------------------------------ -- Time Type -- ------------------------------ type Time_Type_Def is new Duration_Type_Def with null record; -- Get the type name function Get_Name (Type_Def : Time_Type_Def) return String; -- Convert the value into a string. function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String; Time_Type : aliased constant Time_Type_Def := Time_Type_Def '(null record); -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Time_Type_Def) return String is pragma Unreferenced (Type_Def); begin return "Time"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Ada.Calendar.Formatting.Image (Epoch + Value.Time_Value); end To_String; -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in Ada.Calendar.Time) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value - Epoch), Type_Def => Time_Type'Access); end To_Object; function To_Object (Value : in Nullables.Nullable_Time) return Object is begin if Value.Is_Null then return Null_Object; else return To_Object (Value.Value); end if; end To_Object; -- ------------------------------ -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Time (Value : in Object) return Ada.Calendar.Time is begin case Value.V.Of_Type is when TYPE_TIME => return Value.V.Time_Value + Epoch; when TYPE_STRING | TYPE_WIDE_STRING => declare T : constant String := Value.Type_Def.To_String (Value.V); begin return Ada.Calendar.Formatting.Value (T); exception -- Last chance, try to convert a Unix time displayed as an integer. when Constraint_Error => return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (T)); end; when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end To_Time; function To_Time (Value : in Object) return Nullables.Nullable_Time is begin if Is_Null (Value) then return Nullables.Nullable_Time '(Is_Null => True, Value => Epoch); else return Nullables.Nullable_Time '(Is_Null => False, Value => To_Time (Value)); end if; end To_Time; -- ------------------------------ -- Force the object to be a time. -- ------------------------------ function Cast_Time (Value : Object) return Object is begin case Value.V.Of_Type is when TYPE_TIME => return Value; when TYPE_STRING | TYPE_WIDE_STRING => return Time.To_Object (Formatting.Value (Value.Type_Def.To_String (Value.V))); when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end Cast_Time; end Util.Beans.Objects.Time;
Implement To_Object and To_Time with a Nullable_Time type
Implement To_Object and To_Time with a Nullable_Time type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2cc30b2dedadb47cbe9269266f8fbb33357db85c
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wiki.Strings.WString := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
Use the Wiki.Strings.WString type
Use the Wiki.Strings.WString type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c71eea371d89d75c7a6acfb1ab9d876d2e233eec
regtests/asf-rest-tests.adb
regtests/asf-rest-tests.adb
----------------------------------------------------------------------- -- asf-rest-tests - Unit tests for ASF.Rest and ASF.Servlets.Rest -- 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 Util.Log; with Util.Test_Caller; with Util.Measures; with EL.Contexts.Default; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Servlets.Rest; with ASF.Rest.Definition; package body ASF.Rest.Tests is package Caller is new Util.Test_Caller (Test, "Rest"); package Test_API_Definition is new ASF.Rest.Definition (Object_Type => Test_API, URI => "/test"); package API_Create is new Test_API_Definition.Definition (Handler => Create'Access, Method => ASF.Rest.POST, Pattern => "", Permission => 0); package API_Update is new Test_API_Definition.Definition (Handler => Update'Access, Method => ASF.Rest.PUT, Pattern => ":id", Permission => 0); package API_Delete is new Test_API_Definition.Definition (Handler => Delete'Access, Method => ASF.Rest.DELETE, Pattern => ":id", Permission => 0); package API_List is new Test_API_Definition.Definition (Handler => List'Access, Method => ASF.Rest.GET, Pattern => "", Permission => 0); package API_Get is new Test_API_Definition.Definition (Handler => List'Access, Method => ASF.Rest.GET, Pattern => ":id", Permission => 0); procedure Create (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin Reply.Set_Status (ASF.Responses.SC_CREATED); -- ASF.Rest.Created (Reply, "23"); Reply.Set_Header (Name => "Location", Value => "/test/23"); end Create; procedure Update (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Id : constant String := Req.Get_Path_Parameter (1); begin null; end Update; procedure Delete (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin Reply.Set_Status (ASF.Responses.SC_NO_CONTENT); end Delete; procedure List (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin if Req.Get_Path_Parameter_Count = 0 then Stream.Start_Document; Stream.Start_Array ("list"); for I in 1 .. 10 loop Stream.Start_Entity ("item"); Stream.Write_Attribute ("id", I); Stream.Write_Attribute ("name", "Item " & Natural'Image (I)); Stream.End_Entity ("item"); end loop; Stream.End_Array ("list"); Stream.End_Document; else declare Id : constant String := Req.Get_Path_Parameter (1); begin if Id = "100" then Reply.Set_Status (ASF.Responses.SC_NOT_FOUND); elsif Id /= "44" then Reply.Set_Status (ASF.Responses.SC_GONE); end if; end; end if; end List; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Rest.POST API operation", Test_Create'Access); Caller.Add_Test (Suite, "Test ASF.Rest.GET API operation", Test_Get'Access); Caller.Add_Test (Suite, "Test ASF.Rest.PUT API operation", Test_Update'Access); Caller.Add_Test (Suite, "Test ASF.Rest.DELETE API operation", Test_Delete'Access); Caller.Add_Test (Suite, "Test ASF.Rest.TRACE API operation", Test_Invalid'Access); end Add_Tests; procedure Benchmark (Ctx : in ASF.Servlets.Servlet_Registry; Title : in String; Method : in String; URI : in String) is T : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Result : Ada.Strings.Unbounded.Unbounded_String; begin Request.Set_Method (Method); Request.Set_Request_URI (URI); ASF.Servlets.Forward (Dispatcher, Request, Reply); end; end loop; Util.Measures.Report (T, Title, 1000); end Benchmark; procedure Test_Operation (T : in out Test; Method : in String; URI : in String; Status : in Natural) is use ASF.Servlets; use Util.Tests; Ctx : Servlet_Registry; S1 : aliased ASF.Servlets.Rest.Rest_Servlet; EL_Ctx : EL.Contexts.Default.Default_Context; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Ctx.Add_Servlet ("API", S1'Unchecked_Access); Ctx.Start; Ctx.Dump_Routes (Util.Log.INFO_LEVEL); Test_API_Definition.Register (Registry => Ctx, Name => "API", ELContext => EL_Ctx); Request.Set_Method (Method); declare Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Result : Ada.Strings.Unbounded.Unbounded_String; begin Request.Set_Request_URI (URI); Forward (Dispatcher, Request, Reply); -- Check the response after the API method execution. Reply.Read_Content (Result); Assert_Equals (T, Status, Reply.Get_Status, "Invalid status for " & Method & ":" & URI); end; Benchmark (Ctx, Method & " " & URI, Method, URI); end Test_Operation; -- ------------------------------ -- Test REST POST create operation -- ------------------------------ procedure Test_Create (T : in out Test) is begin Test_Operation (T, "POST", "/test", ASF.Responses.SC_CREATED); end Test_Create; -- ------------------------------ -- Test REST PUT update operation -- ------------------------------ procedure Test_Update (T : in out Test) is begin Test_Operation (T, "PUT", "/test/44", ASF.Responses.SC_OK); end Test_Update; -- ------------------------------ -- Test REST GET operation -- ------------------------------ procedure Test_Get (T : in out Test) is begin Test_Operation (T, "GET", "/test", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/test/44", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/test/100", ASF.Responses.SC_NOT_FOUND); end Test_Get; -- ------------------------------ -- Test REST DELETE delete operation -- ------------------------------ procedure Test_Delete (T : in out Test) is begin Test_Operation (T, "DELETE", "/test/44", ASF.Responses.SC_NO_CONTENT); end Test_Delete; -- ------------------------------ -- Test REST operation on invalid operation. -- ------------------------------ procedure Test_Invalid (T : in out Test) is begin Test_Operation (T, "TRACE", "/test/44", ASF.Responses.SC_NOT_FOUND); end Test_Invalid; end ASF.Rest.Tests;
----------------------------------------------------------------------- -- asf-rest-tests - Unit tests for ASF.Rest and ASF.Servlets.Rest -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Test_Caller; with Util.Measures; with EL.Contexts.Default; with Security.Permissions; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Servlets.Rest; with ASF.Rest.Definition; with ASF.Rest.Operation; package body ASF.Rest.Tests is package Caller is new Util.Test_Caller (Test, "Rest"); package Test_Permission is new Security.Permissions.Definition ("test-permission"); package API_Simple_Get is new ASF.Rest.Operation (Handler => Simple_Get'Access, URI => "/simple/:id"); package API_Simple_List is new ASF.Rest.Operation (Handler => Simple_Get'Access, URI => "/simple"); package API_Simple_Post is new ASF.Rest.Operation (Handler => Simple_Post'Access, URI => "/simple", Method => ASF.Rest.POST); package API_Simple_Delete is new ASF.Rest.Operation (Handler => Simple_Delete'Access, URI => "/simple/:id", Method => ASF.Rest.DELETE); package API_Simple_Put is new ASF.Rest.Operation (Handler => Simple_Put'Access, URI => "/simple/:id", Method => ASF.Rest.PUT); package Test_API_Definition is new ASF.Rest.Definition (Object_Type => Test_API, URI => "/test"); package API_Create is new Test_API_Definition.Definition (Handler => Create'Access, Method => ASF.Rest.POST, Pattern => "", Permission => Test_Permission.Permission); package API_Update is new Test_API_Definition.Definition (Handler => Update'Access, Method => ASF.Rest.PUT, Pattern => ":id", Permission => 0); package API_Delete is new Test_API_Definition.Definition (Handler => Delete'Access, Method => ASF.Rest.DELETE, Pattern => ":id", Permission => 0); package API_List is new Test_API_Definition.Definition (Handler => List'Access, Method => ASF.Rest.GET, Pattern => "", Permission => 0); package API_Get is new Test_API_Definition.Definition (Handler => List'Access, Method => ASF.Rest.GET, Pattern => ":id", Permission => 0); procedure Simple_Get (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Data : Test_API; begin List (Data, Req, Reply, Stream); end Simple_Get; procedure Simple_Put (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Data : Test_API; begin Update (Data, Req, Reply, Stream); end Simple_Put; procedure Simple_Post (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Data : Test_API; begin Create (Data, Req, Reply, Stream); end Simple_Post; procedure Simple_Delete (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Data : Test_API; begin Delete (Data, Req, Reply, Stream); end Simple_Delete; procedure Create (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin Reply.Set_Status (ASF.Responses.SC_CREATED); -- ASF.Rest.Created (Reply, "23"); Reply.Set_Header (Name => "Location", Value => "/test/23"); end Create; procedure Update (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is Id : constant String := Req.Get_Path_Parameter (1); begin Reply.Set_Status (ASF.Responses.SC_OK); end Update; procedure Delete (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin Reply.Set_Status (ASF.Responses.SC_NO_CONTENT); end Delete; procedure List (Data : in out Test_API; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class) is begin if Req.Get_Path_Parameter_Count = 0 then Stream.Start_Document; Stream.Start_Array ("list"); for I in 1 .. 10 loop Stream.Start_Entity ("item"); Stream.Write_Attribute ("id", I); Stream.Write_Attribute ("name", "Item " & Natural'Image (I)); Stream.End_Entity ("item"); end loop; Stream.End_Array ("list"); Stream.End_Document; else declare Id : constant String := Req.Get_Path_Parameter (1); begin if Id = "100" then Reply.Set_Status (ASF.Responses.SC_NOT_FOUND); elsif Id /= "44" then Reply.Set_Status (ASF.Responses.SC_GONE); end if; end; end if; end List; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Rest.POST API operation", Test_Create'Access); Caller.Add_Test (Suite, "Test ASF.Rest.GET API operation", Test_Get'Access); Caller.Add_Test (Suite, "Test ASF.Rest.PUT API operation", Test_Update'Access); Caller.Add_Test (Suite, "Test ASF.Rest.DELETE API operation", Test_Delete'Access); Caller.Add_Test (Suite, "Test ASF.Rest.TRACE API operation", Test_Invalid'Access); end Add_Tests; procedure Benchmark (Ctx : in ASF.Servlets.Servlet_Registry; Title : in String; Method : in String; URI : in String) is T : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Result : Ada.Strings.Unbounded.Unbounded_String; begin Request.Set_Method (Method); Request.Set_Request_URI (URI); ASF.Servlets.Forward (Dispatcher, Request, Reply); end; end loop; Util.Measures.Report (T, Title, 1000); end Benchmark; procedure Test_Operation (T : in out Test; Method : in String; URI : in String; Status : in Natural) is use ASF.Servlets; use Util.Tests; Ctx : Servlet_Registry; S1 : aliased ASF.Servlets.Rest.Rest_Servlet; EL_Ctx : EL.Contexts.Default.Default_Context; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Ctx.Add_Servlet ("API", S1'Unchecked_Access); Ctx.Add_Mapping (Name => "API", Pattern => "/simple/*"); Ctx.Start; Ctx.Dump_Routes (Util.Log.INFO_LEVEL); ASF.Rest.Register (Ctx, API_Simple_Get.Definition); ASF.Rest.Register (Ctx, API_Simple_List.Definition); ASF.Rest.Register (Ctx, API_Simple_Post.Definition); ASF.Rest.Register (Ctx, API_Simple_Put.Definition); ASF.Rest.Register (Ctx, API_Simple_Delete.Definition); Ctx.Dump_Routes (Util.Log.INFO_LEVEL); Test_API_Definition.Register (Registry => Ctx, Name => "API", ELContext => EL_Ctx); Request.Set_Method (Method); declare Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Result : Ada.Strings.Unbounded.Unbounded_String; begin Request.Set_Request_URI (URI); Forward (Dispatcher, Request, Reply); -- Check the response after the API method execution. Reply.Read_Content (Result); Assert_Equals (T, Status, Reply.Get_Status, "Invalid status for " & Method & ":" & URI); end; Benchmark (Ctx, Method & " " & URI, Method, URI); end Test_Operation; -- ------------------------------ -- Test REST POST create operation -- ------------------------------ procedure Test_Create (T : in out Test) is begin Test_Operation (T, "POST", "/test", ASF.Responses.SC_CREATED); Test_Operation (T, "POST", "/simple", ASF.Responses.SC_CREATED); end Test_Create; -- ------------------------------ -- Test REST PUT update operation -- ------------------------------ procedure Test_Update (T : in out Test) is begin Test_Operation (T, "PUT", "/test/44", ASF.Responses.SC_OK); Test_Operation (T, "PUT", "/simple/44", ASF.Responses.SC_OK); end Test_Update; -- ------------------------------ -- Test REST GET operation -- ------------------------------ procedure Test_Get (T : in out Test) is begin Test_Operation (T, "GET", "/test", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/test/44", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/test/100", ASF.Responses.SC_NOT_FOUND); Test_Operation (T, "GET", "/simple", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/simple/44", ASF.Responses.SC_OK); Test_Operation (T, "GET", "/simple/100", ASF.Responses.SC_NOT_FOUND); end Test_Get; -- ------------------------------ -- Test REST DELETE delete operation -- ------------------------------ procedure Test_Delete (T : in out Test) is begin Test_Operation (T, "DELETE", "/test/44", ASF.Responses.SC_NO_CONTENT); Test_Operation (T, "DELETE", "/simple/44", ASF.Responses.SC_NO_CONTENT); end Test_Delete; -- ------------------------------ -- Test REST operation on invalid operation. -- ------------------------------ procedure Test_Invalid (T : in out Test) is begin Test_Operation (T, "TRACE", "/test/44", ASF.Responses.SC_NOT_FOUND); Test_Operation (T, "TRACE", "/simple/44", ASF.Responses.SC_NOT_FOUND); end Test_Invalid; end ASF.Rest.Tests;
Add new operations to verify simple REST api support with the ASF.Rest.Operation generic package
Add new operations to verify simple REST api support with the ASF.Rest.Operation generic package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6e60ba99c0fd978a8f94cae6508a33ea40d36498
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 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; -- ------------------------------ -- Format the difference between two event IDs (offset). -- ------------------------------ function Offset (First : in MAT.Events.Event_Id_Type; Second : in MAT.Events.Event_Id_Type) return String is use type MAT.Events.Event_Id_Type; begin if First = Second or First = 0 or Second = 0 then return ""; elsif First > Second then return "+" & Util.Strings.Image (Natural (First - Second)); else return "-" & Util.Strings.Image (Natural (Second - First)); end if; end Offset; -- ------------------------------ -- Format a short description of the memory allocation slot. -- ------------------------------ function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin return Addr (Value) & " is " & Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & " by event" & MAT.Events.Event_Id_Type'Image (Item.Event); end Slot; 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; Hex_Length : Positive := 16; 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, Hex_Length); 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; -- ------------------------------ -- Format the difference between two event IDs (offset). -- ------------------------------ function Offset (First : in MAT.Events.Event_Id_Type; Second : in MAT.Events.Event_Id_Type) return String is use type MAT.Events.Event_Id_Type; begin if First = Second or First = 0 or Second = 0 then return ""; elsif First > Second then return "+" & Util.Strings.Image (Natural (First - Second)); else return "-" & Util.Strings.Image (Natural (Second - First)); end if; end Offset; -- ------------------------------ -- Format a short description of the memory allocation slot. -- ------------------------------ function Slot (Value : in MAT.Types.Target_Addr; Item : in MAT.Memory.Allocation; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin return Addr (Value) & " is " & Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & " by event" & MAT.Events.Event_Id_Type'Image (Item.Event); end Slot; end MAT.Formats;
Define a Hex_Length format and use it for the hexadecimal conversion
Define a Hex_Length format and use it for the hexadecimal conversion
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8f1358c32e582dca21b019523820e4a027202a09
src/asf-rest.ads
src/asf-rest.ads
----------------------------------------------------------------------- -- asf-rest -- REST 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 Util.Strings; with Util.Serialize.IO; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with EL.Contexts; with Security.Permissions; -- == REST == -- The <tt>ASF.Rest</tt> package provides support to implement easily some RESTful API. package ASF.Rest is subtype Request is ASF.Requests.Request; subtype Response is ASF.Responses.Response; subtype Output_Stream is Util.Serialize.IO.Output_Stream; -- The HTTP rest method. type Method_Type is (GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, OPTIONS); type Descriptor is abstract tagged limited private; type Descriptor_Access is access all Descriptor'Class; -- Get the permission index associated with the REST operation. function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index; -- Dispatch the request to the API handler. procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class) is abstract; private type Descriptor is abstract tagged limited record Next : Descriptor_Access; Method : Method_Type; Pattern : Util.Strings.Name_Access; Permission : Security.Permissions.Permission_Index := 0; end record; -- Register the API descriptor in a list. procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access); -- Register the list of API descriptors for a given servlet and a root path. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; URI : in String; ELContext : in EL.Contexts.ELContext'Class; List : in Descriptor_Access); end ASF.Rest;
----------------------------------------------------------------------- -- asf-rest -- REST 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 Util.Strings; with Util.Serialize.IO; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with EL.Contexts; with Security.Permissions; -- == REST == -- The <tt>ASF.Rest</tt> package provides support to implement easily some RESTful API. package ASF.Rest is subtype Request is ASF.Requests.Request; subtype Response is ASF.Responses.Response; subtype Output_Stream is Util.Serialize.IO.Output_Stream; -- The HTTP rest method. type Method_Type is (GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, OPTIONS); type Descriptor is abstract tagged limited private; type Descriptor_Access is access all Descriptor'Class; -- Get the permission index associated with the REST operation. function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index; -- Dispatch the request to the API handler. procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class) is abstract; type Operation_Access is access procedure (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- Register the API definition in the servlet registry. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry'Class; Definition : in Descriptor_Access); private type Descriptor is abstract tagged limited record Next : Descriptor_Access; Method : Method_Type; Pattern : Util.Strings.Name_Access; Permission : Security.Permissions.Permission_Index := 0; end record; -- Register the API descriptor in a list. procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access); -- Register the list of API descriptors for a given servlet and a root path. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; URI : in String; ELContext : in EL.Contexts.ELContext'Class; List : in Descriptor_Access); type Static_Descriptor is new Descriptor with record Handler : Operation_Access; end record; -- Dispatch the request to the API handler. overriding procedure Dispatch (Handler : in Static_Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class); end ASF.Rest;
Declare Register, Static_Descriptor type for the ASF.Rest.Operation generic package
Declare Register, Static_Descriptor type for the ASF.Rest.Operation generic package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
26f8c20c4af818c9a4f8a4d0c7dfb2b48b9f7ec1
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- 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 Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "href" then declare URI : Unbounded_Wide_Wide_String; Exists : Boolean; begin Engine.Links.Make_Page_Link (Value, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); end; elsif Value'Length = 0 then return; elsif Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Render a quote. -- ------------------------------ procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Value'Length = 0 then return; elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("q"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("q"); end Render_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (BOLD => HTML_BOLD'Access, ITALIC => HTML_ITALIC'Access, CODE => HTML_CODE'Access, SUPERSCRIPT => HTML_SUPERSCRIPT'Access, SUBSCRIPT => HTML_SUBSCRIPT'Access, STRIKEOUT => HTML_STRIKEOUT'Access, PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Output.Write (To_Wide_Wide_String (Text)); else Document.Output.Start_Element ("pre"); -- Document.Output.Write_Wide_Text (Text); Document.Output.End_Element ("pre"); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Doc, Node.Preformatted, ""); when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- 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 Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "href" then declare URI : Unbounded_Wide_Wide_String; Exists : Boolean; begin Engine.Links.Make_Page_Link (Value, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); end; elsif Value'Length = 0 then return; elsif Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Render a quote. -- ------------------------------ procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Value'Length = 0 then return; elsif Name = "cite" or Name = "title" or Name = "lang" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("q"); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("q"); end Render_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (BOLD => HTML_BOLD'Access, ITALIC => HTML_ITALIC'Access, CODE => HTML_CODE'Access, SUPERSCRIPT => HTML_SUPERSCRIPT'Access, SUBSCRIPT => HTML_SUBSCRIPT'Access, STRIKEOUT => HTML_STRIKEOUT'Access, PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String) is begin Engine.Close_Paragraph; if Format = "html" then Engine.Output.Write (Text); else Engine.Output.Start_Element ("pre"); Engine.Output.Write_Wide_Text (Text); Engine.Output.End_Element ("pre"); end if; end Render_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Rename Add_Preformatted into Render_Preformatted and update for the new implementation
Rename Add_Preformatted into Render_Preformatted and update for the new implementation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0ab4655e7f693f3235d9cbb2df671ae031424312
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to 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. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Document : in out Wiki_Renderer; Format : in Documents.Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); -- Set the text style format. procedure Set_Format (Document : in out Wiki_Renderer; Format : in Documents.Format_Map); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Documents.Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Add Escape_Rule enum
Add Escape_Rule enum
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e4ac71c327a8ab40cb465176e6d464ed7e8bfbcd
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- 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 Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Default Security Controllers -- ------------------------------ -- The <b>Auth_Controller</b> grants the permission if there is a principal. type Auth_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- The <b>Pass_Through_Controller</b> grants access to anybody. type Pass_Through_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). -- ------------------------------ overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then Log.Debug ("Grant permission because a principal exists"); return True; else return False; end if; end Has_Permission; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Context, Permission); begin Log.Debug ("Pass through controller grants the permission"); return True; end Has_Permission; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Finish_Config; type Policy_Fields is (FIELD_ALL_PERMISSION, FIELD_AUTH_PERMISSION); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is Name : constant String := Util.Beans.Objects.To_String (Value); begin case Field is when FIELD_ALL_PERMISSION => P.Add_Permission (Name, new Pass_Through_Controller); when FIELD_AUTH_PERMISSION => P.Add_Permission (Name, new Auth_Controller); end case; end Set_Member; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class, Element_Type_Access => Policy_Manager_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; begin Policy_Mapping.Add_Mapping ("all-permission/name", FIELD_ALL_PERMISSION); Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION); end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- 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 Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Default Security Controllers -- ------------------------------ -- The <b>Auth_Controller</b> grants the permission if there is a principal. type Auth_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- The <b>Pass_Through_Controller</b> grants access to anybody. type Pass_Through_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). -- ------------------------------ overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then Log.Debug ("Grant permission because a principal exists"); return True; else return False; end if; end Has_Permission; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Context, Permission); begin Log.Debug ("Pass through controller grants the permission"); return True; end Has_Permission; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Finish_Config; type Policy_Fields is (FIELD_GRANT_PERMISSION, FIELD_AUTH_PERMISSION); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is Name : constant String := Util.Beans.Objects.To_String (Value); begin case Field is when FIELD_GRANT_PERMISSION => P.Add_Permission (Name, new Pass_Through_Controller); when FIELD_AUTH_PERMISSION => P.Add_Permission (Name, new Auth_Controller); end case; end Set_Member; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class, Element_Type_Access => Policy_Manager_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; begin Policy_Mapping.Add_Mapping ("grant-permission/name", FIELD_GRANT_PERMISSION); Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION); end Security.Policies;
Rename the <all-permission> into <grant-permission>
Rename the <all-permission> into <grant-permission>
Ada
apache-2.0
stcarrez/ada-security
606e00f8580750e2e3e9b516753325fc6ed98bcc
src/util-encoders-aes.ads
src/util-encoders-aes.ads
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key; Rounds : Natural := 0; end record; end Util.Encoders.AES;
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key; Rounds : Natural := 0; end record; type Encoder is new Util.Encoders.Transformer with record Key : Key_Type; Mode : AES_Mode := CBC; end record; end Util.Encoders.AES;
Declare the Set_Key function with AES_Mode enum
Declare the Set_Key function with AES_Mode enum
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a338127859e12e966611a85dfbe196f5de42d20b
regtests/util-texts-builders_tests.ads
regtests/util-texts-builders_tests.ads
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016, 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.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the iterate operation. procedure Test_Inline_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the tail operation. procedure Test_Tail (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016, 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.Texts.Builders_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the length operation. procedure Test_Length (T : in out Test); -- Test the append operation. procedure Test_Append (T : in out Test); -- Test the append operation. procedure Test_Inline_Append (T : in out Test); -- Test the iterate operation. procedure Test_Iterate (T : in out Test); -- Test the iterate operation. procedure Test_Inline_Iterate (T : in out Test); -- Test the clear operation. procedure Test_Clear (T : in out Test); -- Test the tail operation. procedure Test_Tail (T : in out Test); -- Test the append and iterate performance. procedure Test_Perf (T : in out Test); end Util.Texts.Builders_Tests;
Declare the Test_Inline_Append procedure
Declare the Test_Inline_Append procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
936f304dae5ab4f5c6c134a7b66610ef7eb26e24
mat/src/events/mat-events-probes.ads
mat/src/events/mat-events-probes.ads
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- 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; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; package MAT.Events.Probes is ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message; Event : in out MAT.Events.Targets.Target_Event) is abstract; procedure Execute (Probe : in Probe_Type; Event : in MAT.Events.Targets.Target_Event) is abstract; ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- 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; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is type Probe_Event_Type is record Event : MAT.Events.Internal_Reference; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Probe_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in MAT.Events.Targets.Target_Event) is abstract; ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Probe_Event_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
Define the Probe_Event_Type and use it in the Probe manager
Define the Probe_Event_Type and use it in the Probe manager
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6ace2d3996cb88042328629ccee76d10cee139b0
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Implement new function Get_Policy Keep the policy index in the policy instance
Implement new function Get_Policy Keep the policy index in the policy instance
Ada
apache-2.0
stcarrez/ada-security
c0763fb5f32fb4b2511e1ecbd43f31f17777a4d3
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy defines and implements the set of security rules that specify -- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains -- the security policies. These policies are registered when an application starts -- and before reading the policy configuration files. -- -- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads -- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Document the security policy
Document the security policy
Ada
apache-2.0
stcarrez/ada-security
71cddba0c44029cddd99c6f50aeee2a819f9d9f5
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin loop Peek (P, C); exit when C = ';'; if Len < Name'Last then Len := Len + 1; end if; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin loop Peek (P, C); exit when C = ';'; if Len < Name'Last then Len := Len + 1; end if; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; end Parse_Entity; end Wiki.Parsers.Html;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
78ed396e86d684e74ccc8e56106e60c79df3b85f
components/src/camera/OV2640/bit_fields.ads
components/src/camera/OV2640/bit_fields.ads
with HAL; use HAL; package Bit_Fields is type Bit_Field is array (Natural range <>) of Bit with Component_Size => 1; function To_Word (Bits : Bit_Field) return Word with Pre => Bits'First = 0 and then Bits'Last = 31; function To_Short (Bits : Bit_Field) return Short with Pre => Bits'First = 0 and then Bits'Last = 15; function To_Byte (Bits : Bit_Field) return Byte with Pre => Bits'First = 0 and then Bits'Last = 7; function To_Bit_Field (Value : Word) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 31; function To_Bit_Field (Value : Short) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 15; function To_Bit_Field (Value : Byte) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 7; end Bit_Fields;
with HAL; use HAL; package Bit_Fields is type Bit_Field is array (Natural range <>) of Bit with Component_Size => 1; function To_Word (Bits : Bit_Field) return Word; function To_Short (Bits : Bit_Field) return Short; function To_Byte (Bits : Bit_Field) return Byte; function To_Bit_Field (Value : Word) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 31; function To_Bit_Field (Value : Short) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 15; function To_Bit_Field (Value : Byte) return Bit_Field with Post => To_Bit_Field'Result'First = 0 and then To_Bit_Field'Result'Last = 7; end Bit_Fields;
Remove useless preconditions in bit_fields.ads
Remove useless preconditions in bit_fields.ads
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
e304f6f09818089e337362e28cfc0761e2ddda45
orka/src/orka/implementation/orka-rendering-programs-modules.adb
orka/src/orka/implementation/orka-rendering-programs-modules.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.Logging.Default; with Orka.Strings; with Orka.Terminals; package body Orka.Rendering.Programs.Modules is use all type Orka.Logging.Default_Module; use all type Orka.Logging.Severity; procedure Log is new Orka.Logging.Default.Generic_Log (Renderer); function Trim_Image (Value : Integer) return String is (Orka.Strings.Trim (Integer'Image (Value))); package L1 renames Ada.Characters.Latin_1; use Orka.Strings; procedure Log_Error_With_Source (Text, Info_Log, Message : String) is package SF renames Ada.Strings.Fixed; Extra_Rows : constant := 1; Line_Number_Padding : constant := 2; Separator : constant String := " | "; use SF; use all type Orka.Terminals.Color; use all type Orka.Terminals.Style; begin declare Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3); Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2); Message_Kind_Color : constant Orka.Terminals.Color := (if +Message_Parts (1) = "error" then Red elsif +Message_Parts (1) = "warning" then Yellow elsif +Message_Parts (1) = "note" then Cyan else Default); Message_Kind : constant String := Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color); Message_Value : constant String := Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold); ------------------------------------------------------------------------- Lines : constant Orka.Strings.String_List := Split (Text, "" & L1.LF); Error_Row : constant Positive := Positive'Value (+Split (+Log_Parts (2), "(", 2) (1)); First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows); Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows); Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding; begin Log (Error, Message); for Row_Index in First_Row .. Last_Row loop declare Row_Image : constant String := SF.Tail (Trim (Row_Index'Image), Line_Digits); Row_Image_Colorized : constant String := Orka.Terminals.Colorize (Row_Image, Attribute => Dark); Line_Image : constant String := +Lines (Row_Index); First_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward); Last_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward); Error_Indicator : constant String := Orka.Terminals.Colorize (Natural'Max (0, First_Index_Line - 1) * " " & (Last_Index_Line - First_Index_Line + 1) * "^", Foreground => Green, Attribute => Bold); Prefix_Image : constant String := (Row_Image'Length + Separator'Length) * " "; begin Log (Error, Row_Image_Colorized & Separator & Line_Image); if Row_Index = Error_Row then Log (Error, Prefix_Image & Error_Indicator); Log (Error, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value); end if; end; end loop; end; exception when others => -- Continue if parsing Info_Log fails null; end Log_Error_With_Source; procedure Load_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Location : Resources.Locations.Location_Ptr; Path : String) is begin if Path /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); Source : constant Resources.Byte_Array_Pointers.Pointer := Location.Read_Data (Path); Text : String renames Resources.Convert (Source.Get); begin Shader.Set_Source (Text); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF); begin for Part of Log_Parts loop Log_Error_With_Source (Text, +Part, "Compiling shader " & Path & " failed:"); end loop; raise Shader_Compile_Error with Path & ":" & Log; end; end if; Log (Debug, "Compiled shader " & Path); Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Text)) & " lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)"); Log (Debug, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Load_And_Compile; procedure Set_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Source : String) is begin if Source /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); begin Shader.Set_Source (Source); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF); begin for Part of Log_Parts loop Log_Error_With_Source (Source, +Part, "Compiling " & Shader_Kind'Image & " shader failed:"); end loop; raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log; end; end if; Log (Debug, "Compiled string with " & Trim_Image (Source'Length) & " characters"); Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Source)) & " lines"); Log (Debug, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Set_And_Compile; function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Set_And_Compile (Result, Vertex_Shader, VS); Set_And_Compile (Result, Tess_Control_Shader, TCS); Set_And_Compile (Result, Tess_Evaluation_Shader, TES); Set_And_Compile (Result, Geometry_Shader, GS); Set_And_Compile (Result, Fragment_Shader, FS); Set_And_Compile (Result, Compute_Shader, CS); end return; end Create_Module_From_Sources; function Create_Module (Location : Resources.Locations.Location_Ptr; VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Load_And_Compile (Result, Vertex_Shader, Location, VS); Load_And_Compile (Result, Tess_Control_Shader, Location, TCS); Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES); Load_And_Compile (Result, Geometry_Shader, Location, GS); Load_And_Compile (Result, Fragment_Shader, Location, FS); Load_And_Compile (Result, Compute_Shader, Location, CS); end return; end Create_Module; procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is use GL.Objects.Shaders; procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is Holder : Shader_Holder.Holder renames Subject.Shaders (Stage); begin if not Holder.Is_Empty then Program.GL_Program.Attach (Holder.Element); end if; end Attach; begin for Module of Modules loop Attach (Module, Vertex_Shader); Attach (Module, Tess_Control_Shader); Attach (Module, Tess_Evaluation_Shader); Attach (Module, Geometry_Shader); Attach (Module, Fragment_Shader); Attach (Module, Compute_Shader); end loop; end Attach_Shaders; procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is use GL.Objects.Shaders; procedure Detach (Holder : Shader_Holder.Holder) is begin if not Holder.Is_Empty then Program.GL_Program.Detach (Holder.Element); end if; end Detach; begin for Module of Modules loop Detach (Module.Shaders (Vertex_Shader)); Detach (Module.Shaders (Tess_Control_Shader)); Detach (Module.Shaders (Tess_Evaluation_Shader)); Detach (Module.Shaders (Geometry_Shader)); Detach (Module.Shaders (Fragment_Shader)); Detach (Module.Shaders (Compute_Shader)); end loop; end Detach_Shaders; end Orka.Rendering.Programs.Modules;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.Logging.Default; with Orka.Strings; with Orka.Terminals; package body Orka.Rendering.Programs.Modules is use all type Orka.Logging.Default_Module; use all type Orka.Logging.Severity; procedure Log is new Orka.Logging.Default.Generic_Log (Renderer); function Trim_Image (Value : Integer) return String is (Orka.Strings.Trim (Integer'Image (Value))); package L1 renames Ada.Characters.Latin_1; use Orka.Strings; procedure Log_Error_With_Source (Text, Info_Log : String) is package SF renames Ada.Strings.Fixed; Extra_Rows : constant := 1; Line_Number_Padding : constant := 2; Separator : constant String := " | "; use SF; use all type Orka.Terminals.Color; use all type Orka.Terminals.Style; begin declare Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3); Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2); Message_Kind_Color : constant Orka.Terminals.Color := (if +Message_Parts (1) = "error" then Red elsif +Message_Parts (1) = "warning" then Yellow elsif +Message_Parts (1) = "note" then Cyan else Default); Log_Severity : constant Orka.Logging.Severity := (if +Message_Parts (1) = "error" then Error elsif +Message_Parts (1) = "warning" then Warning elsif +Message_Parts (1) = "note" then Info else Error); Message_Kind : constant String := Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color); Message_Value : constant String := Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold); ------------------------------------------------------------------------- Lines : constant Orka.Strings.String_List := Split (Text, "" & L1.LF); Error_Row : constant Positive := Positive'Value (+Split (+Log_Parts (2), "(", 2) (1)); First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows); Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows); Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding; begin for Row_Index in First_Row .. Last_Row loop declare Row_Image : constant String := SF.Tail (Trim (Row_Index'Image), Line_Digits); Row_Image_Colorized : constant String := Orka.Terminals.Colorize (Row_Image, Attribute => Dark); Line_Image : constant String := +Lines (Row_Index); First_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward); Last_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward); Error_Indicator : constant String := Orka.Terminals.Colorize (Natural'Max (0, First_Index_Line - 1) * " " & (Last_Index_Line - First_Index_Line + 1) * "^", Foreground => Green, Attribute => Bold); Prefix_Image : constant String := (Row_Image'Length + Separator'Length) * " "; begin Log (Log_Severity, Row_Image_Colorized & Separator & Line_Image); if Row_Index = Error_Row then Log (Log_Severity, Prefix_Image & Error_Indicator); Log (Log_Severity, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value); end if; end; end loop; end; exception when others => -- Continue if parsing Info_Log fails null; end Log_Error_With_Source; use all type GL.Objects.Shaders.Shader_Type; function Image (Kind : GL.Objects.Shaders.Shader_Type) return String is (case Kind is when Vertex_Shader => "vertex shader", when Fragment_Shader => "fragment shader", when Geometry_Shader => "geometry shader", when Tess_Evaluation_Shader => "tesselation evaluation shader", when Tess_Control_Shader => "tesselation control shader", when Compute_Shader => "compute shader"); procedure Load_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Location : Resources.Locations.Location_Ptr; Path : String) is begin if Path /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); Source : constant Resources.Byte_Array_Pointers.Pointer := Location.Read_Data (Path); Text : String renames Resources.Convert (Source.Get); begin Shader.Set_Source (Text); Shader.Compile; if not Shader.Compile_Status then declare Shader_Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Shader_Log, "" & L1.LF); begin Log (Error, "Compiling shader " & Path & " failed:"); for Part of Log_Parts loop Log_Error_With_Source (Text, +Part); end loop; raise Shader_Compile_Error with Path & ":" & Shader_Log; end; end if; Log (Info, "Compiled " & Image (Shader_Kind) & " " & Path); Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Text)) & " lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)"); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Load_And_Compile; procedure Set_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Source : String) is begin if Source /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); begin Shader.Set_Source (Source); Shader.Compile; if not Shader.Compile_Status then declare Shader_Log : constant String := Shader.Info_Log; Log_Parts : constant Orka.Strings.String_List := Split (Shader_Log, "" & L1.LF); begin Log (Error, "Compiling " & Shader_Kind'Image & " shader failed:"); for Part of Log_Parts loop Log_Error_With_Source (Source, +Part); end loop; raise Shader_Compile_Error with Shader_Kind'Image & ":" & Shader_Log; end; end if; Log (Debug, "Compiled " & Image (Shader_Kind) & " text with " & Trim_Image (Source'Length) & " characters"); Log (Debug, " size: " & Trim_Image (Orka.Strings.Lines (Source)) & " lines"); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Set_And_Compile; function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Set_And_Compile (Result, Vertex_Shader, VS); Set_And_Compile (Result, Tess_Control_Shader, TCS); Set_And_Compile (Result, Tess_Evaluation_Shader, TES); Set_And_Compile (Result, Geometry_Shader, GS); Set_And_Compile (Result, Fragment_Shader, FS); Set_And_Compile (Result, Compute_Shader, CS); end return; end Create_Module_From_Sources; function Create_Module (Location : Resources.Locations.Location_Ptr; VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Load_And_Compile (Result, Vertex_Shader, Location, VS); Load_And_Compile (Result, Tess_Control_Shader, Location, TCS); Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES); Load_And_Compile (Result, Geometry_Shader, Location, GS); Load_And_Compile (Result, Fragment_Shader, Location, FS); Load_And_Compile (Result, Compute_Shader, Location, CS); end return; end Create_Module; procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is use GL.Objects.Shaders; procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is Holder : Shader_Holder.Holder renames Subject.Shaders (Stage); begin if not Holder.Is_Empty then Program.GL_Program.Attach (Holder.Element); end if; end Attach; begin for Module of Modules loop Attach (Module, Vertex_Shader); Attach (Module, Tess_Control_Shader); Attach (Module, Tess_Evaluation_Shader); Attach (Module, Geometry_Shader); Attach (Module, Fragment_Shader); Attach (Module, Compute_Shader); end loop; end Attach_Shaders; procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is use GL.Objects.Shaders; procedure Detach (Holder : Shader_Holder.Holder) is begin if not Holder.Is_Empty then Program.GL_Program.Detach (Holder.Element); end if; end Detach; begin for Module of Modules loop Detach (Module.Shaders (Vertex_Shader)); Detach (Module.Shaders (Tess_Control_Shader)); Detach (Module.Shaders (Tess_Evaluation_Shader)); Detach (Module.Shaders (Geometry_Shader)); Detach (Module.Shaders (Fragment_Shader)); Detach (Module.Shaders (Compute_Shader)); end loop; end Detach_Shaders; end Orka.Rendering.Programs.Modules;
Fix level of log messages for shader info log
orka: Fix level of log messages for shader info log Use Warning or Info as the level when a message in the info log of a shader which failed to compile is prefixed with "warning:" or "note:". Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
4ae257e8e39ca4a4a4d3ee93c6327d45cf17ad1b
src/sys/os-windows/util-systems-os.ads
src/sys/os-windows/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- 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; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "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; 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; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; 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 := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "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; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; 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 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 := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; -- pragma Pack (Startup_Info); 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; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- 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; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "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; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; 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 := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "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; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; 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 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; -- pragma Pack (Startup_Info); 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; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); 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; pragma Import (Stdcall, Create_File, "CreateFileW"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Add Create_File and its flags to create/open a windows file
Add Create_File and its flags to create/open a windows file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
09dea50616f68bd44730fa746a6686cf558cc6e9
awa/plugins/awa-storages/regtests/awa-storages-tests.adb
awa/plugins/awa-storages/regtests/awa-storages-tests.adb
----------------------------------------------------------------------- -- awa-storages-tests -- Unit tests for storages module -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ADO; with Servlet.Streams; with ASF.Tests; with AWA.Tests.Helpers.Users; with AWA.Storages.Beans; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Storages.Modules; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Storages.Tests is use Ada.Strings.Unbounded; use AWA.Tests; use type AWA.Storages.Services.Storage_Service_Access; package Caller is new Util.Test_Caller (Test, "Storages.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Beans.Create", Test_Create_Document'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Servlets (missing)", Test_Missing_Document'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-anonymous-list.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-list.html"); ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply, "List of documents is invalid"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of document by simulating web requests. -- ------------------------------ procedure Test_Create_Document (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("folder-name", "Test Folder Name"); Request.Set_Parameter ("storage-folder-create-form", "1"); Request.Set_Parameter ("storage-folder-create-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html", "folder-create-form.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response after folder creation"); ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-list.html"); ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply, "List of documents is invalid (title)"); ASF.Tests.Assert_Contains (T, "Test Folder Name", Reply, "List of documents is invalid (content)"); end Test_Create_Document; -- ------------------------------ -- Test getting a document which does not exist. -- ------------------------------ procedure Test_Missing_Document (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/files/12345345/view/missing.pdf", "storage-file-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Page not found./title.", Reply, "Page for a missing document is invalid", Servlet.Responses.SC_NOT_FOUND); end Test_Missing_Document; end AWA.Storages.Tests;
----------------------------------------------------------------------- -- awa-storages-tests -- Unit tests for storages module -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with ASF.Tests; with AWA.Tests.Helpers.Users; with Servlet.requests.Mockup; with Servlet.Responses.Mockup; package body AWA.Storages.Tests is package Caller is new Util.Test_Caller (Test, "Storages.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Beans.Create", Test_Create_Document'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Servlets (missing)", Test_Missing_Document'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-anonymous-list.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-list.html"); ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply, "List of documents is invalid"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of document by simulating web requests. -- ------------------------------ procedure Test_Create_Document (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("folder-name", "Test Folder Name"); Request.Set_Parameter ("storage-folder-create-form", "1"); Request.Set_Parameter ("storage-folder-create-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/storages/forms/folder-create.html", "folder-create-form.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response after folder creation"); ASF.Tests.Do_Get (Request, Reply, "/storages/documents.html", "storage-list.html"); ASF.Tests.Assert_Contains (T, "Documents of the workspace", Reply, "List of documents is invalid (title)"); ASF.Tests.Assert_Contains (T, "Test Folder Name", Reply, "List of documents is invalid (content)"); end Test_Create_Document; -- ------------------------------ -- Test getting a document which does not exist. -- ------------------------------ procedure Test_Missing_Document (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/storages/files/12345345/view/missing.pdf", "storage-file-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Page not found./title.", Reply, "Page for a missing document is invalid", Servlet.Responses.SC_NOT_FOUND); end Test_Missing_Document; end AWA.Storages.Tests;
Fix various compilation and style warnings
Fix various compilation and style warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a65aa6603a3c2220a60cb45fb5dd035a51d7230e
regtests/ado-tests.ads
regtests/ado-tests.ads
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record I1 : Integer; I2 : Integer; end record; procedure Set_Up (T : in out Test); procedure Test_Load (T : in out Test); procedure Test_Create_Load (T : in out Test); procedure Test_Not_Open (T : in out Test); procedure Test_Allocate (T : in out Test); procedure Test_Create_Save (T : in out Test); procedure Test_Perf_Create_Save (T : in out Test); procedure Test_Delete_All (T : in out Test); -- Test string insert. procedure Test_String (T : in out Test); -- Test blob insert. procedure Test_Blob (T : in out Test); end ADO.Tests;
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record I1 : Integer; I2 : Integer; end record; procedure Set_Up (T : in out Test); procedure Test_Load (T : in out Test); procedure Test_Create_Load (T : in out Test); procedure Test_Not_Open (T : in out Test); procedure Test_Allocate (T : in out Test); procedure Test_Create_Save (T : in out Test); procedure Test_Perf_Create_Save (T : in out Test); procedure Test_Delete_All (T : in out Test); -- Test string insert. procedure Test_String (T : in out Test); -- Test blob insert. procedure Test_Blob (T : in out Test); -- Test the To_Object and To_Identifier operations. procedure Test_Identifier_To_Object (T : in out Test); end ADO.Tests;
Declare Test_Identifier_To_Object test procedure
Declare Test_Identifier_To_Object test procedure
Ada
apache-2.0
stcarrez/ada-ado
93342a3147116ba437255797313507da493fff95
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- 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 Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Declare the protected procedure Iterate to iterate over a list of events
Declare the protected procedure Iterate to iterate over a list of events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
72a851094895e81089a0439d668efe9ff0c47f2f
mat/src/mat-targets-readers.adb
mat/src/mat-targets-readers.adb
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; 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)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); For_Servant.Process.Events := For_Servant.Events; MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Reader.Set_Target_Events (Process_Reader.Events); Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; 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)); -- ------------------------------ -- Create a new process after the begin event is received from the event stream. -- ------------------------------ procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String) is begin For_Servant.Target.Create_Process (Pid => Pid, Path => Path, Process => For_Servant.Process); For_Servant.Process.Events := For_Servant.Events; MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Pid : MAT.Types.Target_Process_Ref := 0; Path : Ada.Strings.Unbounded.Unbounded_String; begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_PID => Pid := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_EXE => Path := MAT.Readers.Marshaller.Get_String (Msg.Buffer); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; For_Servant.Create_Process (Pid, Path); For_Servant.Reader.Read_Message (Msg); For_Servant.Reader.Read_Event_Definitions (Msg); end Probe_Begin; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => For_Servant.Probe_Begin (Id, Params.all, Frame, Msg); when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Process_Reader.Events := Reader.Get_Target_Events; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
Update the Initialize procedure to use the new Get_Target_Events function
Update the Initialize procedure to use the new Get_Target_Events function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
74d3f2dd6f8d2ea97ca7714373e75a8d5bdcebaa
matp/src/events/mat-events-timelines.ads
matp/src/events/mat-events-timelines.ads
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Expressions; with MAT.Events.Tools; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector); -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map); -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map); end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Expressions; with MAT.Events.Tools; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector); -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map); -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map); -- Collect the events that match the filter and append them to the events vector. procedure Filter_Events (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Events : in out MAT.Events.Tools.Target_Event_Vector); end MAT.Events.Timelines;
Declare the Filter_Events procedure
Declare the Filter_Events procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a6b3820cfc2abd1dee7aaad61c6b53fa5dfec6e7
awa/plugins/awa-tags/src/awa-tags-components.ads
awa/plugins/awa-tags/src/awa-tags-components.ads
----------------------------------------------------------------------- -- awa-tags-components -- Tags component -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Strings.Vectors; with EL.Expressions; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; with ASF.Factory; -- == Tags Component == -- -- === Displaying a list of tags === -- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as -- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the -- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to -- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated -- against that variable and the result defines the link. -- -- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- var="tagName" -- tagClass="tagedit-listelement tagedit-listelement-old"/> -- -- === Tag editing === -- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given -- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this, -- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource. -- -- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an -- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must -- be a <tt>Tag_List_Bean</tt> object. -- -- <awa:tagList value='#{question.tags}' id='qtags' -- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/> -- -- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and -- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were -- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt> -- phase (ie, before calling the action's bean operation). -- package AWA.Tags.Components is use ASF.Contexts.Writer; -- Get the Tags component factory. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <ul class='taglist'> -- <li><span>tag</span></li> -- </ul> -- -- or -- -- <input type='text' name='' value='tag'/> -- type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record -- List of tags that have been added. Added : Util.Strings.Vectors.Vector; -- List of tags that have been removed. Deleted : Util.Strings.Vectors.Vector; -- True if the submitted values are correct. Is_Valid : Boolean := False; end record; type Tag_UIInput_Access is access all Tag_UIInput'Class; -- Returns True if the tag component must be rendered as readonly. function Is_Readonly (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Get the tag after convertion with the optional converter. function Get_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the tag as a readonly item. procedure Render_Readonly_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag as a link. procedure Render_Link_Tag (UI : in Tag_UIInput; Name : in String; Tag : in Util.Beans.Objects.Object; Link : in EL.Expressions.Expression; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag for an input form. procedure Render_Form_Tag (UI : in Tag_UIInput; Id : in String; Tag : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>. procedure Render_Readonly (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags for a form. procedure Render_Form (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the javascript to enable the tag edition. procedure Render_Script (UI : in Tag_UIInput; Id : in String; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return EL.Expressions.Method_Expression; -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out Tag_UIInput; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end AWA.Tags.Components;
----------------------------------------------------------------------- -- awa-tags-components -- Tags component -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Strings.Vectors; with EL.Expressions; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; with ASF.Factory; with AWA.Tags.Models; -- == Tags Component == -- -- === Displaying a list of tags === -- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as -- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the -- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to -- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated -- against that variable and the result defines the link. -- -- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- var="tagName" -- tagClass="tagedit-listelement tagedit-listelement-old"/> -- -- === Tag editing === -- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given -- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this, -- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource. -- -- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an -- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must -- be a <tt>Tag_List_Bean</tt> object. -- -- <awa:tagList value='#{question.tags}' id='qtags' -- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/> -- -- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and -- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were -- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt> -- phase (ie, before calling the action's bean operation). -- -- === Tag cloud === -- The <tt>awa:tagCloud</tt> component displays a list of tags as a tag cloud. -- The tags list passed in the <tt>value</tt> attribute must inherit from the -- <tt>Tag_Info_List_Bean</tt> type which indicates for each tag the number of -- times it is used. -- -- <awa:tagCloud value='#{questionTagList}' id='cloud' styleClass="tag-cloud" -- var="tagName" rows="30" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- tagClass="tag-link"/> -- package AWA.Tags.Components is use ASF.Contexts.Writer; -- Get the Tags component factory. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <ul class='taglist'> -- <li><span>tag</span></li> -- </ul> -- -- or -- -- <input type='text' name='' value='tag'/> -- type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record -- List of tags that have been added. Added : Util.Strings.Vectors.Vector; -- List of tags that have been removed. Deleted : Util.Strings.Vectors.Vector; -- True if the submitted values are correct. Is_Valid : Boolean := False; end record; type Tag_UIInput_Access is access all Tag_UIInput'Class; -- Returns True if the tag component must be rendered as readonly. function Is_Readonly (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Get the tag after convertion with the optional converter. function Get_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the tag as a readonly item. procedure Render_Readonly_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag as a link. procedure Render_Link_Tag (UI : in Tag_UIInput; Name : in String; Tag : in Util.Beans.Objects.Object; Link : in EL.Expressions.Expression; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag for an input form. procedure Render_Form_Tag (UI : in Tag_UIInput; Id : in String; Tag : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>. procedure Render_Readonly (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags for a form. procedure Render_Form (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the javascript to enable the tag edition. procedure Render_Script (UI : in Tag_UIInput; Id : in String; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return EL.Expressions.Method_Expression; -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out Tag_UIInput; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Tag Cloud Component -- ------------------------------ -- The tag cloud component type Tag_UICloud is new ASF.Components.Html.UIHtmlComponent with null record; type Tag_Info_Array is array (Positive range <>) of AWA.Tags.Models.Tag_Info; type Tag_Info_Array_Access is access all Tag_Info_Array; -- Render the tag cloud component. overriding procedure Encode_Children (UI : in Tag_UICloud; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags. If the <tt>tagLink</tt> attribute is defined, a link -- is rendered for each tag. procedure Render_Cloud (UI : in Tag_UICloud; List : in Tag_Info_Array; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end AWA.Tags.Components;
Define the <awa:tagCloud> component to render a list of tags as a cloud
Define the <awa:tagCloud> component to render a list of tags as a cloud
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
d78303fe6cbdeeae3939f958cd222b12cd4f1228
src/gen-artifacts-docs-googlecode.adb
src/gen-artifacts-docs-googlecode.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Write_Line (File, "{{{"); when L_END_CODE => Formatter.Write_Line (File, "}}}"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "= " & Line.Content & " ="); when L_HEADER_2 => Formatter.Write_Line (File, "== " & Line.Content & " =="); when L_HEADER_3 => Formatter.Write_Line (File, "=== " & Line.Content & " ==="); when L_HEADER_4 => Formatter.Write_Line (File, "==== " & Line.Content & " ===="); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter, Document); begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Write_Line (File, "{{{"); when L_END_CODE => Formatter.Write_Line (File, "}}}"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "= " & Line.Content & " ="); when L_HEADER_2 => Formatter.Write_Line (File, "== " & Line.Content & " =="); when L_HEADER_3 => Formatter.Write_Line (File, "=== " & Line.Content & " ==="); when L_HEADER_4 => Formatter.Write_Line (File, "==== " & Line.Content & " ===="); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end if; end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
Print the footer reference link only when Print_Footer is set
Print the footer reference link only when Print_Footer is set
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo