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
9b5aa7850eaf67d5d925df6d8ba9d40ec1eabd3c
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Make the Sizes_Command a public procedure
Make the Sizes_Command a public procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a6593e016d402f285fca5938611710076f1b3ec6
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- 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.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Declare the Event_Command procedure
Declare the Event_Command procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a6ad70772c29d84c9d129f69202ddc291533a925
matp/src/mat-formats.adb
matp/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (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.Targets.Probe_Event_Type; Last : in MAT.Events.Targets.Probe_Event_Type) return String is use type MAT.Events.Targets.Event_Id_Type; Id1 : constant String := MAT.Events.Targets.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Targets.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.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; 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.Targets.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & ")"; end if; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the PID into a string. -- ------------------------------ function Pid (Value : in MAT.Types.Target_Process_Ref) return String is begin return Util.Strings.Image (Natural (Value)); end Pid; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format an event range description. -- ------------------------------ function Event (First : in MAT.Events.Targets.Probe_Event_Type; Last : in MAT.Events.Targets.Probe_Event_Type) return String is use type MAT.Events.Targets.Event_Id_Type; Id1 : constant String := MAT.Events.Targets.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Targets.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.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; 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.Targets.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & ")"; end if; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Implement the Pid function
Implement the Pid function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d83899e8eadafd485038471c3c1dd622fe6e4de5
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 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;
----------------------------------------------------------------------- -- 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); -- Set a timer to be called after the given time span. procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; In_Time : in Ada.Real_Time.Time_Span); -- 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;
Declare a Set_Timer procedure which uses a Time_Span as parameter
Declare a Set_Timer procedure which uses a Time_Span as parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bb60808866257336375fc84b1f6e615835870f0c
awa/src/awa-commands.adb
awa/src/awa-commands.adb
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 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.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with AWA.Applications.Configs; with Keystore.Passwords.Input; with Keystore.Passwords.Files; with Keystore.Passwords.Unsafe; with Keystore.Passwords.Cmds; package body AWA.Commands is use type Keystore.Passwords.Provider_Access; use type Keystore.Header_Slot_Count_Type; use type Keystore.Passwords.Keys.Key_Provider_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands"); procedure Load_Configuration (Context : in out Context_Type) is begin begin Context.File_Config.Load_Properties (Context.Config_File.all); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file {0}", Context.Config_File.all); end; if Context.File_Config.Exists (GPG_CRYPT_CONFIG) then Context.GPG.Set_Encrypt_Command (Context.File_Config.Get (GPG_CRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_DECRYPT_CONFIG) then Context.GPG.Set_Decrypt_Command (Context.File_Config.Get (GPG_DECRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_LIST_CONFIG) then Context.GPG.Set_List_Key_Command (Context.File_Config.Get (GPG_LIST_CONFIG)); end if; Context.Config.Randomize := not Context.Zero; end Load_Configuration; -- ------------------------------ -- Returns True if a keystore is used by the configuration and must be unlocked. -- ------------------------------ function Use_Keystore (Context : in Context_Type) return Boolean is begin if Context.Wallet_File'Length > 0 then return True; end if; return Context.File_Config.Exists ("keystore.path"); end Use_Keystore; -- ------------------------------ -- Open the keystore file using the password password. -- ------------------------------ procedure Open_Keystore (Context : in out Context_Type) is begin Setup_Password_Provider (Context); Setup_Key_Provider (Context); Context.Wallet.Open (Path => Context.Get_Keystore_Path, Data_Path => Context.Data_Path.all, Config => Context.Config, Info => Context.Info); if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then if Context.Key_Provider /= null then Context.Wallet.Set_Master_Key (Context.Key_Provider.all); end if; if Context.Provider = null then Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False); end if; Context.Wallet.Unlock (Context.Provider.all, Context.Slot); else Context.GPG.Load_Secrets (Context.Wallet); Context.Wallet.Set_Master_Key (Context.GPG); Context.Wallet.Unlock (Context.GPG, Context.Slot); end if; Keystore.Properties.Initialize (Context.Secure_Config, Context.Wallet'Unchecked_Access); AWA.Applications.Configs.Merge (Context.App_Config, Context.File_Config, Context.Secure_Config, ""); end Open_Keystore; -- ------------------------------ -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. -- ------------------------------ procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type) is Path : constant String := AWA.Applications.Configs.Get_Config_Path (Name); begin begin Context.File_Config.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => null; end; if Context.Use_Keystore then Open_Keystore (Context); else Context.App_Config := Context.File_Config; end if; Application.Initialize (Context.App_Config, Context.Factory); end Configure; -- ------------------------------ -- Initialize the commands. -- ------------------------------ overriding procedure Initialize (Context : in out Context_Type) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => -("akt - tool to store and protect your sensitive data")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Version'Access, Switch => "-V", Long_Switch => "--version", Help => -("Print the version")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Verbose'Access, Switch => "-v", Long_Switch => "--verbose", Help => -("Verbose execution mode")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Debug'Access, Switch => "-vv", Long_Switch => "--debug", Help => -("Enable debug execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Dump'Access, Switch => "-vvv", Long_Switch => "--debug-dump", Help => -("Enable debug dump execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Zero'Access, Switch => "-z", Long_Switch => "--zero", Help => -("Erase and fill with zeros instead of random values")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Config_File'Access, Switch => "-c:", Long_Switch => "--config=", Argument => "PATH", Help => -("Defines the path for configuration file")); GC.Initialize_Option_Scan (Stop_At_First_Non_Switch => True); -- Driver.Set_Description (-("akt - tool to store and protect your sensitive data")); -- Driver.Set_Usage (-("[-V] [-v] [-vv] [-vvv] [-c path] [-t count] [-z] " & -- "<command> [<args>]" & ASCII.LF & -- "where:" & ASCII.LF & -- " -V Print the tool version" & ASCII.LF & -- " -v Verbose execution mode" & ASCII.LF & -- " -vv Debug execution mode" & ASCII.LF & -- " -vvv Dump execution mode" & ASCII.LF & -- " -c path Defines the path for akt " & -- "global configuration" & ASCII.LF & -- " -t count Number of threads for the " & -- "encryption/decryption process" & ASCII.LF & -- " -z Erase and fill with zeros instead of random values")); -- Driver.Add_Command ("help", -- -("print some help"), -- Help_Command'Access); end Initialize; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Context.Wallet_File'Access, Switch => "-k:", Long_Switch => "--keystore=", Argument => "PATH", Help => -("Defines the path for the keystore file")); GC.Define_Switch (Config => Config, Output => Context.Data_Path'Access, Switch => "-d:", Long_Switch => "--data-path=", Argument => "PATH", Help => -("The directory which contains the keystore data blocks")); GC.Define_Switch (Config => Config, Output => Context.Password_File'Access, Long_Switch => "--passfile=", Argument => "PATH", Help => -("Read the file that contains the password")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passfd=", Argument => "NUM", Help => -("Read the password from the pipe with" & " the given file descriptor")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passsocket=", Help => -("The password is passed within the socket connection")); GC.Define_Switch (Config => Config, Output => Context.Password_Env'Access, Long_Switch => "--passenv=", Argument => "NAME", Help => -("Read the environment variable that contains" & " the password (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Switch => "-p:", Long_Switch => "--password=", Help => -("The password is passed within the command line (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Password_Askpass'Access, Long_Switch => "--passask", Help => -("Run the ssh-askpass command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Password_Command'Access, Long_Switch => "--passcmd=", Argument => "COMMAND", Help => -("Run the command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Wallet_Key_File'Access, Long_Switch => "--wallet-key-file=", Argument => "PATH", Help => -("Read the file that contains the wallet keys")); end Setup; procedure Setup_Password_Provider (Context : in out Context_Type) is begin if Context.Password_Askpass then Context.Provider := Keystore.Passwords.Cmds.Create ("ssh-askpass"); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Password_File'Length > 0 then Context.Provider := Keystore.Passwords.Files.Create (Context.Password_File.all); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Unsafe_Password'Length > 0 then Context.Provider := Keystore.Passwords.Unsafe.Create (Context.Unsafe_Password.all); else Context.No_Password_Opt := True; end if; Context.Key_Provider := Keystore.Passwords.Keys.Create (Keystore.DEFAULT_WALLET_KEY); end Setup_Password_Provider; procedure Setup_Key_Provider (Context : in out Context_Type) is begin if Context.Wallet_Key_File'Length > 0 then Context.Key_Provider := Keystore.Passwords.Files.Create (Context.Wallet_Key_File.all); end if; end Setup_Key_Provider; -- ------------------------------ -- Get the keystore file path. -- ------------------------------ function Get_Keystore_Path (Context : in out Context_Type) return String is begin if Context.Wallet_File'Length > 0 then Context.First_Arg := 1; return Context.Wallet_File.all; else raise Error with "No keystore path"; end if; end Get_Keystore_Path; overriding procedure Finalize (Context : in out Context_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Keystore.Passwords.Provider'Class, Name => Keystore.Passwords.Provider_Access); begin GC.Free (Context.Command_Config); Free (Context.Provider); end Finalize; end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 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.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with AWA.Applications.Configs; with Keystore.Passwords.Input; with Keystore.Passwords.Files; with Keystore.Passwords.Unsafe; with Keystore.Passwords.Cmds; package body AWA.Commands is use type Keystore.Passwords.Provider_Access; use type Keystore.Header_Slot_Count_Type; use type Keystore.Passwords.Keys.Key_Provider_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands"); procedure Load_Configuration (Context : in out Context_Type) is begin begin Context.File_Config.Load_Properties (Context.Config_File.all); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read server configuration file '{0}'", Context.Config_File.all); end; if Context.File_Config.Exists (GPG_CRYPT_CONFIG) then Context.GPG.Set_Encrypt_Command (Context.File_Config.Get (GPG_CRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_DECRYPT_CONFIG) then Context.GPG.Set_Decrypt_Command (Context.File_Config.Get (GPG_DECRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_LIST_CONFIG) then Context.GPG.Set_List_Key_Command (Context.File_Config.Get (GPG_LIST_CONFIG)); end if; Context.Config.Randomize := not Context.Zero; end Load_Configuration; -- ------------------------------ -- Returns True if a keystore is used by the configuration and must be unlocked. -- ------------------------------ function Use_Keystore (Context : in Context_Type) return Boolean is begin if Context.Wallet_File'Length > 0 then return True; end if; return Context.File_Config.Exists ("keystore.path"); end Use_Keystore; -- ------------------------------ -- Open the keystore file using the password password. -- ------------------------------ procedure Open_Keystore (Context : in out Context_Type) is begin Setup_Password_Provider (Context); Setup_Key_Provider (Context); Context.Wallet.Open (Path => Context.Get_Keystore_Path, Data_Path => Context.Data_Path.all, Config => Context.Config, Info => Context.Info); if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then if Context.Key_Provider /= null then Context.Wallet.Set_Master_Key (Context.Key_Provider.all); end if; if Context.Provider = null then Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False); end if; Context.Wallet.Unlock (Context.Provider.all, Context.Slot); else Context.GPG.Load_Secrets (Context.Wallet); Context.Wallet.Set_Master_Key (Context.GPG); Context.Wallet.Unlock (Context.GPG, Context.Slot); end if; Keystore.Properties.Initialize (Context.Secure_Config, Context.Wallet'Unchecked_Access); AWA.Applications.Configs.Merge (Context.App_Config, Context.File_Config, Context.Secure_Config, ""); end Open_Keystore; -- ------------------------------ -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. -- ------------------------------ procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type) is Path : constant String := AWA.Applications.Configs.Get_Config_Path (Name); begin begin Context.File_Config.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => null; end; if Context.Use_Keystore then Open_Keystore (Context); else Context.App_Config := Context.File_Config; end if; Application.Initialize (Context.App_Config, Context.Factory); end Configure; -- ------------------------------ -- Initialize the commands. -- ------------------------------ overriding procedure Initialize (Context : in out Context_Type) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => -("akt - tool to store and protect your sensitive data")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Version'Access, Switch => "-V", Long_Switch => "--version", Help => -("Print the version")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Verbose'Access, Switch => "-v", Long_Switch => "--verbose", Help => -("Verbose execution mode")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Debug'Access, Switch => "-vv", Long_Switch => "--debug", Help => -("Enable debug execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Dump'Access, Switch => "-vvv", Long_Switch => "--debug-dump", Help => -("Enable debug dump execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Zero'Access, Switch => "-z", Long_Switch => "--zero", Help => -("Erase and fill with zeros instead of random values")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Config_File'Access, Switch => "-c:", Long_Switch => "--config=", Argument => "PATH", Help => -("Defines the path for configuration file")); GC.Initialize_Option_Scan (Stop_At_First_Non_Switch => True); -- Driver.Set_Description (-("akt - tool to store and protect your sensitive data")); -- Driver.Set_Usage (-("[-V] [-v] [-vv] [-vvv] [-c path] [-t count] [-z] " & -- "<command> [<args>]" & ASCII.LF & -- "where:" & ASCII.LF & -- " -V Print the tool version" & ASCII.LF & -- " -v Verbose execution mode" & ASCII.LF & -- " -vv Debug execution mode" & ASCII.LF & -- " -vvv Dump execution mode" & ASCII.LF & -- " -c path Defines the path for akt " & -- "global configuration" & ASCII.LF & -- " -t count Number of threads for the " & -- "encryption/decryption process" & ASCII.LF & -- " -z Erase and fill with zeros instead of random values")); -- Driver.Add_Command ("help", -- -("print some help"), -- Help_Command'Access); end Initialize; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Context.Wallet_File'Access, Switch => "-k:", Long_Switch => "--keystore=", Argument => "PATH", Help => -("Defines the path for the keystore file")); GC.Define_Switch (Config => Config, Output => Context.Data_Path'Access, Switch => "-d:", Long_Switch => "--data-path=", Argument => "PATH", Help => -("The directory which contains the keystore data blocks")); GC.Define_Switch (Config => Config, Output => Context.Password_File'Access, Long_Switch => "--passfile=", Argument => "PATH", Help => -("Read the file that contains the password")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passfd=", Argument => "NUM", Help => -("Read the password from the pipe with" & " the given file descriptor")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passsocket=", Help => -("The password is passed within the socket connection")); GC.Define_Switch (Config => Config, Output => Context.Password_Env'Access, Long_Switch => "--passenv=", Argument => "NAME", Help => -("Read the environment variable that contains" & " the password (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Switch => "-p:", Long_Switch => "--password=", Help => -("The password is passed within the command line (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Password_Askpass'Access, Long_Switch => "--passask", Help => -("Run the ssh-askpass command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Password_Command'Access, Long_Switch => "--passcmd=", Argument => "COMMAND", Help => -("Run the command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Wallet_Key_File'Access, Long_Switch => "--wallet-key-file=", Argument => "PATH", Help => -("Read the file that contains the wallet keys")); end Setup_Command; procedure Setup_Password_Provider (Context : in out Context_Type) is begin if Context.Password_Askpass then Context.Provider := Keystore.Passwords.Cmds.Create ("ssh-askpass"); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Password_File'Length > 0 then Context.Provider := Keystore.Passwords.Files.Create (Context.Password_File.all); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Unsafe_Password'Length > 0 then Context.Provider := Keystore.Passwords.Unsafe.Create (Context.Unsafe_Password.all); else Context.No_Password_Opt := True; end if; Context.Key_Provider := Keystore.Passwords.Keys.Create (Keystore.DEFAULT_WALLET_KEY); end Setup_Password_Provider; procedure Setup_Key_Provider (Context : in out Context_Type) is begin if Context.Wallet_Key_File'Length > 0 then Context.Key_Provider := Keystore.Passwords.Files.Create (Context.Wallet_Key_File.all); end if; end Setup_Key_Provider; -- ------------------------------ -- Get the keystore file path. -- ------------------------------ function Get_Keystore_Path (Context : in out Context_Type) return String is begin if Context.Wallet_File'Length > 0 then Context.First_Arg := 1; return Context.Wallet_File.all; else raise Error with "No keystore path"; end if; end Get_Keystore_Path; overriding procedure Finalize (Context : in out Context_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Keystore.Passwords.Provider'Class, Name => Keystore.Passwords.Provider_Access); begin GC.Free (Context.Command_Config); Free (Context.Provider); end Finalize; end AWA.Commands;
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6a30cceffa660097b36bf585879dbe7a32c17456
matp/src/events/mat-events-targets.adb
matp/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Events.Targets is ITERATE_COUNT : constant Event_Id_Type := 10_000; -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; -- ------------------------------ -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)) is First_Event : Target_Event; Last_Event : Target_Event; First_Id : Event_Id_Type; begin Target.Get_Limits (First_Event, Last_Event); First_Id := First_Event.Id; while First_Id < Last_Event.Id loop -- Iterate over the events in groups of 10_000 to release the lock and give some -- opportunity to the server thread to add new events. Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Process); First_Id := First_Id + ITERATE_COUNT; end loop; end Iterate; -- ------------------------------ -- Release the storage allocated for the events. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Events) is begin Target.Events.Clear; end Finalize; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; -- ------------------------------ -- Clear the events. -- ------------------------------ procedure Clear is procedure Free is new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access); begin while not Events.Is_Empty loop declare Block : Event_Block_Access := Events.First_Element; begin Free (Block); Events.Delete_First; end; end loop; Current := null; Last_Id := 0; Ids.Clear; end Clear; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Events.Targets is ITERATE_COUNT : constant Event_Id_Type := 10_000; -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Target_Event; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Extract from the frame info map, the list of event info sorted on the count. -- ------------------------------ procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector) is function "<" (Left, Right : in Event_Info_Type) return Boolean is begin return Left.Count < Right.Count; end "<"; package Sort_Event_Info is new Event_Info_Vectors.Generic_Sorting; Iter : Frame_Event_Info_Cursor := Map.First; Item : Event_Info_Type; begin while Frame_Event_Info_Maps.Has_Element (Iter) loop Item := Frame_Event_Info_Maps.Element (Iter); List.Append (Item); Frame_Event_Info_Maps.Next (Iter); end loop; Sort_Event_Info.Sort (List); end Build_Event_Info; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; -- ------------------------------ -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)) is First_Event : Target_Event; Last_Event : Target_Event; First_Id : Event_Id_Type; begin Target.Get_Limits (First_Event, Last_Event); First_Id := First_Event.Id; while First_Id < Last_Event.Id loop -- Iterate over the events in groups of 10_000 to release the lock and give some -- opportunity to the server thread to add new events. Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Process); First_Id := First_Id + ITERATE_COUNT; end loop; end Iterate; -- ------------------------------ -- Release the storage allocated for the events. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Events) is begin Target.Events.Clear; end Finalize; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; -- ------------------------------ -- Clear the events. -- ------------------------------ procedure Clear is procedure Free is new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access); begin while not Events.Is_Empty loop declare Block : Event_Block_Access := Events.First_Element; begin Free (Block); Events.Delete_First; end; end loop; Current := null; Last_Id := 0; Ids.Clear; end Clear; end Event_Collector; end MAT.Events.Targets;
Fix insertion of event blocks in the Ids map so that the block key correspond to the first event in the block
Fix insertion of event blocks in the Ids map so that the block key correspond to the first event in the block
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4eee3910b5b4e568101341f4eb26ab29f6b16884
matp/src/events/mat-events-targets.ads
matp/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- 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 Ada.Finalization; 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 (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); 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; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type; type Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); 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 first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); 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 first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- 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 new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); 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 Ada.Finalization; 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 (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); 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; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type; type Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); 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 first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); 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 first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- 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)); -- Clear the events. procedure Clear; 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 new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
Declare the protected procedure Clear
Declare the protected procedure Clear
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c8cdb8fe150194eda91b60e43d0d5dd59fda8625
regtests/util-serialize-io-form-tests.adb
regtests/util-serialize-io-form-tests.adb
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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 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.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is 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); T.Assert (P.Has_Error, "No error detected for '" & Content & "'"); end Check_Parse_Error; begin Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is 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); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); 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.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, 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 => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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 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.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is 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); T.Assert (P.Has_Error, "No error detected for '" & Content & "'"); end Check_Parse_Error; begin Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is 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); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); 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.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, 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 => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
Remove unecessary use clauses
Remove unecessary use clauses
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2915825d9bb554f1f15e86e462790ecf6f811433
src/util-streams-buffered.adb
src/util-streams-buffered.adb
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Char : in Character) is begin if Stream.Write_Pos > Stream.Last then Stream.Flush; if Stream.Write_Pos > Stream.Last then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char)); Stream.Write_Pos := Stream.Write_Pos + 1; end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Buffered_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Stream.Write (Character'Val (Val)); elsif Val <= 16#07FF# then Stream.Write (Character'Val (16#C0# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); elsif Val <= 16#0FFFF# then Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); else Val := Val and 16#1FFFFF#; Stream.Write (Character'Val (16#F0# or Shift_Right (Val, 18))); Val := Val and 16#3FFFF#; Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in String) is Start : Positive := Item'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Natural; Size : Natural; Char : Character; begin while Start <= Item'Last loop Size := Item'Last - Start + 1; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; while Size > 0 loop Char := Item (Start); Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char)); Pos := Pos + 1; Start := Start + 1; Size := Size - 1; end loop; Stream.Write_Pos := Pos; end loop; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- 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 Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Char : in Character) is begin if Stream.Write_Pos > Stream.Last then Stream.Flush; if Stream.Write_Pos > Stream.Last then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char)); Stream.Write_Pos := Stream.Write_Pos + 1; end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Buffered_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Stream.Write (Character'Val (Val)); elsif Val <= 16#07FF# then Stream.Write (Character'Val (16#C0# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); elsif Val <= 16#0FFFF# then Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); else Val := Val and 16#1FFFFF#; Stream.Write (Character'Val (16#F0# or Shift_Right (Val, 18))); Val := Val and 16#3FFFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in String) is Start : Positive := Item'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Natural; Size : Natural; Char : Character; begin while Start <= Item'Last loop Size := Item'Last - Start + 1; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; while Size > 0 loop Char := Item (Start); Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char)); Pos := Pos + 1; Start := Start + 1; Size := Size - 1; end loop; Stream.Write_Pos := Pos; end loop; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- 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 Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
Fix UTF-8 4-byte sequence
Fix UTF-8 4-byte sequence
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2e6b5e880fe1f45d39331661543dae568a3f613e
tools/druss-commands-ping.ads
tools/druss-commands-ping.ads
----------------------------------------------------------------------- -- druss-commands-ping -- Ping devices from the gateway -- 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. ----------------------------------------------------------------------- package Druss.Commands.Ping is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type); -- Execute a ping from the gateway to each device. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Ping;
----------------------------------------------------------------------- -- druss-commands-ping -- Ping devices from the gateway -- 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. ----------------------------------------------------------------------- package Druss.Commands.Ping is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type); -- Execute a ping from the gateway to each device. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Ping;
Add a device selector to the Do_Ping procedure
Add a device selector to the Do_Ping procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
bd6db87d130ec19ebbfd1a1bc8f2266935973fe6
awa/plugins/awa-storages/src/awa-storages-beans.ads
awa/plugins/awa-storages/src/awa-storages-beans.ads
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Upload_Bean bean instance. function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Storages.Models; with AWA.Storages.Modules; with ASF.Parts; with ADO; with Util.Beans.Objects; with Util.Beans.Basic; package AWA.Storages.Beans is FOLDER_ID_PARAMETER : constant String := "folderId"; -- ------------------------------ -- Upload Bean -- ------------------------------ -- The <b>Upload_Bean</b> allows to upload a file in the storage space. type Upload_Bean is new AWA.Storages.Models.Upload_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; Folder_Id : ADO.Identifier; end record; type Upload_Bean_Access is access all Upload_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Save the uploaded file in the storage service. -- @method procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class); -- Upload the file. overriding procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the file. overriding procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish the file. overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Upload_Bean bean instance. function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Folder Bean -- ------------------------------ -- The <b>Folder_Bean</b> allows to create or update the folder name. type Folder_Bean is new AWA.Storages.Models.Storage_Folder_Ref and Util.Beans.Basic.Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; end record; type Folder_Bean_Access is access all Folder_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the folder. procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Init_Flag is (INIT_FOLDER, INIT_FOLDER_LIST, INIT_FILE_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Storage List Bean -- ------------------------------ -- This bean represents a list of storage files for a given folder. type Storage_List_Bean is new AWA.Storages.Models.Storage_List_Bean with record Module : AWA.Storages.Modules.Storage_Module_Access := null; -- Current folder. Folder : aliased Folder_Bean; Folder_Bean : Folder_Bean_Access; -- List of folders. Folder_List : aliased AWA.Storages.Models.Folder_Info_List_Bean; Folder_List_Bean : AWA.Storages.Models.Folder_Info_List_Bean_Access; -- List of files. Files_List : aliased AWA.Storages.Models.Storage_Info_List_Bean; Files_List_Bean : AWA.Storages.Models.Storage_Info_List_Bean_Access; Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Storage_List_Bean_Access is access all Storage_List_Bean'Class; -- Load the folder instance. procedure Load_Folder (Storage : in Storage_List_Bean); -- Load the list of folders. procedure Load_Folders (Storage : in Storage_List_Bean); -- Load the list of files associated with the current folder. procedure Load_Files (Storage : in Storage_List_Bean); overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the files and folder information. overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Folder_List_Bean bean instance. function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Storage_List_Bean bean instance. function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Storages.Beans;
Use the UML AWA.Storages.Models.Storage_List_Bean type and override the Load procedure
Use the UML AWA.Storages.Models.Storage_List_Bean type and override the Load procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9e4f29dedccebd763dbb68353849a3a9cbcd4250
src/orka/implementation/orka-programs.adb
src/orka/implementation/orka-programs.adb
-- Copyright (c) 2015 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 Orka.Programs.Modules; with Orka.Programs.Uniforms; package body Orka.Programs is package Program_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Program); Current_Program : Program_Holder.Holder; function Create_Program (Modules : Programs.Modules.Module_Array; Separable : Boolean := False) return Program is use type GL.Types.Int; begin return Result : Program do -- Attach all shaders to the program before linking Programs.Modules.Attach_Shaders (Modules, Result); Result.GL_Program.Link; if not Result.GL_Program.Link_Status then raise Program_Link_Error with Result.GL_Program.Info_Log; end if; -- Construct arrays of subroutine indices per shader kind Result.Has_Subroutines := False; Result.Subroutines_Modified := False; for Shader_Kind in Programs.Modules.Non_Compute_Shader_Type loop declare Locations : constant GL.Types.Size := Result.GL_Program.Subroutine_Uniform_Locations (Shader_Kind); subtype Indices_Array is GL.Types.UInt_Array (0 .. Locations - 1); begin if Indices_Array'Length > 0 then Result.Has_Subroutines := True; end if; Result.Subroutines (Shader_Kind) := Subroutines_Holder.To_Holder (Indices_Array'(others => GL.Types.UInt'Last)); end; end loop; end return; end Create_Program; function Create_Program (Module : Programs.Modules.Module; Separable : Boolean := False) return Program is begin return Create_Program (Modules.Module_Array'(1 => Module)); end Create_Program; function GL_Program (Object : Program) return GL.Objects.Programs.Program is (Object.GL_Program); function Has_Subroutines (Object : Program) return Boolean is (Object.Has_Subroutines); procedure Use_Subroutines (Object : in out Program) is begin for Shader_Kind in Programs.Modules.Non_Compute_Shader_Type loop declare Indices : GL.Types.UInt_Array renames Object.Subroutines (Shader_Kind).Element; begin if Indices'Length > 0 then GL.Objects.Programs.Set_Uniform_Subroutines (Shader_Kind, Indices); end if; end; end loop; Object.Subroutines_Modified := False; end Use_Subroutines; procedure Use_Program (Object : in out Program) is begin if Current_Program.Is_Empty or else Object /= Current_Program.Element then Object.GL_Program.Use_Program; Current_Program.Replace_Element (Object); if Object.Has_Subroutines then Object.Use_Subroutines; end if; elsif Object.Subroutines_Modified then Object.Use_Subroutines; end if; end Use_Program; function Attribute_Location (Object : Program; Name : String) return GL.Attributes.Attribute is begin return Object.GL_Program.Attrib_Location (Name); end Attribute_Location; procedure Set_Subroutine_Function (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Location : Uniform_Location; Index : Subroutine_Index) is procedure Set_Index (Indices : in out GL.Types.UInt_Array) is begin Indices (Location) := Index; end Set_Index; begin Object.Subroutines (Shader).Update_Element (Set_Index'Access); Object.Subroutines_Modified := True; end Set_Subroutine_Function; function Uniform_Sampler (Object : Program; Name : String) return Uniforms.Uniform_Sampler is begin return Uniforms.Create_Uniform_Sampler (Object, Name); end Uniform_Sampler; function Uniform_Image (Object : Program; Name : String) return Uniforms.Uniform_Image is begin return Uniforms.Create_Uniform_Image (Object, Name); end Uniform_Image; function Uniform_Subroutine (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Name : String) return Uniforms.Uniform_Subroutine is begin return Uniforms.Create_Uniform_Subroutine (Object, Shader, Name); end Uniform_Subroutine; function Uniform_Block (Object : Program; Name : String) return Uniforms.Uniform_Block is begin return Uniforms.Create_Uniform_Block (Object, Name); end Uniform_Block; function Uniform (Object : Program; Name : String) return Uniforms.Uniform is begin return Uniforms.Create_Uniform_Variable (Object, Name); end Uniform; end Orka.Programs;
-- Copyright (c) 2015 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 Orka.Programs.Modules; with Orka.Programs.Uniforms; package body Orka.Programs is package Program_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => Program); Current_Program : Program_Holder.Holder; function Create_Program (Modules : Programs.Modules.Module_Array; Separable : Boolean := False) return Program is use type GL.Types.Int; begin return Result : Program do -- Attach all shaders to the program before linking Programs.Modules.Attach_Shaders (Modules, Result); Result.GL_Program.Set_Separable (Separable); Result.GL_Program.Link; if not Result.GL_Program.Link_Status then raise Program_Link_Error with Result.GL_Program.Info_Log; end if; -- Construct arrays of subroutine indices per shader kind Result.Has_Subroutines := False; Result.Subroutines_Modified := False; for Shader_Kind in Programs.Modules.Non_Compute_Shader_Type loop declare Locations : constant GL.Types.Size := Result.GL_Program.Subroutine_Uniform_Locations (Shader_Kind); subtype Indices_Array is GL.Types.UInt_Array (0 .. Locations - 1); begin if Indices_Array'Length > 0 then Result.Has_Subroutines := True; end if; Result.Subroutines (Shader_Kind) := Subroutines_Holder.To_Holder (Indices_Array'(others => GL.Types.UInt'Last)); end; end loop; end return; end Create_Program; function Create_Program (Module : Programs.Modules.Module; Separable : Boolean := False) return Program is begin return Create_Program (Modules.Module_Array'(1 => Module), Separable); end Create_Program; function GL_Program (Object : Program) return GL.Objects.Programs.Program is (Object.GL_Program); function Has_Subroutines (Object : Program) return Boolean is (Object.Has_Subroutines); procedure Use_Subroutines (Object : in out Program) is begin for Shader_Kind in Programs.Modules.Non_Compute_Shader_Type loop declare Indices : GL.Types.UInt_Array renames Object.Subroutines (Shader_Kind).Element; begin if Indices'Length > 0 then GL.Objects.Programs.Set_Uniform_Subroutines (Shader_Kind, Indices); end if; end; end loop; Object.Subroutines_Modified := False; end Use_Subroutines; procedure Use_Program (Object : in out Program) is begin if Current_Program.Is_Empty or else Object /= Current_Program.Element then Object.GL_Program.Use_Program; Current_Program.Replace_Element (Object); if Object.Has_Subroutines then Object.Use_Subroutines; end if; elsif Object.Subroutines_Modified then Object.Use_Subroutines; end if; end Use_Program; function Attribute_Location (Object : Program; Name : String) return GL.Attributes.Attribute is begin return Object.GL_Program.Attrib_Location (Name); end Attribute_Location; procedure Set_Subroutine_Function (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Location : Uniform_Location; Index : Subroutine_Index) is procedure Set_Index (Indices : in out GL.Types.UInt_Array) is begin Indices (Location) := Index; end Set_Index; begin Object.Subroutines (Shader).Update_Element (Set_Index'Access); Object.Subroutines_Modified := True; end Set_Subroutine_Function; function Uniform_Sampler (Object : Program; Name : String) return Uniforms.Uniform_Sampler is begin return Uniforms.Create_Uniform_Sampler (Object, Name); end Uniform_Sampler; function Uniform_Image (Object : Program; Name : String) return Uniforms.Uniform_Image is begin return Uniforms.Create_Uniform_Image (Object, Name); end Uniform_Image; function Uniform_Subroutine (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Name : String) return Uniforms.Uniform_Subroutine is begin return Uniforms.Create_Uniform_Subroutine (Object, Shader, Name); end Uniform_Subroutine; function Uniform_Block (Object : Program; Name : String) return Uniforms.Uniform_Block is begin return Uniforms.Create_Uniform_Block (Object, Name); end Uniform_Block; function Uniform (Object : Program; Name : String) return Uniforms.Uniform is begin return Uniforms.Create_Uniform_Variable (Object, Name); end Uniform; end Orka.Programs;
Make a program separable according to function parameter
orka: Make a program separable according to function parameter Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
a54b6cc3590843c0d7e993bcd498a9ba4bbdb767
awa/src/awa-audits-services.adb
awa/src/awa-audits-services.adb
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- 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 Ada.Calendar; with Util.Beans.Objects; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Audits.Models; with AWA.Services.Contexts; package body AWA.Audits.Services is package ASC renames AWA.Services.Contexts; package UBO renames Util.Beans.Objects; use type ASC.Service_Context_Access; -- ------------------------------ -- Save the audit changes in the database. -- ------------------------------ overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array) is pragma Unreferenced (Manager); Context : constant ASC.Service_Context_Access := ASC.Current; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : AWA.Audits.Models.Audit_Ref; begin Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); Audit.Set_Entity_Type (Kind); if UBO.Is_Null (C.Old_Value) then Audit.Set_Old_Value (ADO.Null_String); else Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); end if; if UBO.Is_Null (C.New_Value) then Audit.Set_New_Value (ADO.Null_String); else Audit.Set_New_Value (UBO.To_String (C.New_Value)); end if; Audit.Set_Date (Now); if Context /= null then Audit.Set_Session (Context.Get_User_Session); end if; Audit.Save (Session); end; end loop; end Save; end AWA.Audits.Services;
----------------------------------------------------------------------- -- awa-audits-services -- AWA Audit Manager -- 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 Ada.Calendar; with Ada.Strings.Hash; with Util.Strings; with Util.Beans.Objects; with Util.Log.Loggers; with ADO.Objects; with ADO.Schemas; with ADO.Sessions.Entities; with AWA.Audits.Models; with AWA.Services.Contexts; package body AWA.Audits.Services is package ASC renames AWA.Services.Contexts; package UBO renames Util.Beans.Objects; use type ASC.Service_Context_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Audits.Services"); function Hash (Item : in Field_Key) return Ada.Containers.Hash_Type is use type Ada.Containers.Hash_Type; begin return Ada.Containers.Hash_Type (Item.Entity) + Ada.Strings.Hash (Item.Name); end Hash; -- ------------------------------ -- Save the audit changes in the database. -- ------------------------------ overriding procedure Save (Manager : in out Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in ADO.Audits.Auditable_Object_Record'Class; Changes : in ADO.Audits.Audit_Array) is Context : constant ASC.Service_Context_Access := ASC.Current; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Class : constant ADO.Schemas.Class_Mapping_Access := Object.Get_Key.Of_Class; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : AWA.Audits.Models.Audit_Ref; Field : constant Util.Strings.Name_Access := Class.Members (C.Field); begin Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); Audit.Set_Entity_Type (Kind); Audit.Set_Field (Manager.Get_Audit_Field (Field.all, Kind)); if UBO.Is_Null (C.Old_Value) then Audit.Set_Old_Value (ADO.Null_String); else Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); end if; if UBO.Is_Null (C.New_Value) then Audit.Set_New_Value (ADO.Null_String); else Audit.Set_New_Value (UBO.To_String (C.New_Value)); end if; Audit.Set_Date (Now); if Context /= null then Audit.Set_Session (Context.Get_User_Session); end if; Audit.Save (Session); end; end loop; end Save; -- ------------------------------ -- Find the audit field identification number from the entity type and field name. -- ------------------------------ function Get_Audit_Field (Manager : in Audit_Manager; Name : in String; Entity : in ADO.Entity_Type) return ADO.Identifier is Key : constant Field_Key := Field_Key '(Len => Name'Length, Name => Name, Entity => Entity); Pos : constant Audit_Field_Maps.Cursor := Manager.Fields.Find (Key); begin if Audit_Field_Maps.Has_Element (Pos) then return Audit_Field_Maps.Element (Pos); else Log.Warn ("Audit field {0} for {1} not found", Name, ADO.Entity_Type'Image (Entity)); return ADO.NO_IDENTIFIER; end if; end Get_Audit_Field; end AWA.Audits.Services;
Implement Get_Audit_Field and Hash
Implement Get_Audit_Field and Hash
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d9a8470c8c64eb86989c35332c10ef6cfd487206
awa/plugins/awa-blogs/src/awa-blogs-services.ads
awa/plugins/awa-blogs/src/awa-blogs-services.ads
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- 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 ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package AWA.Blogs.Services is NAME : constant String := "Blog_Service"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Permission_ACL ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Permission_ACL ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Permission_ACL ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Permission_ACL ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Permission_ACL ("blog-update-post"); -- Exception raised when a post cannot be found. Not_Found : exception; type Blog_Service is new AWA.Modules.Module_Manager with private; type Blog_Service_Access is access all Blog_Service'Class; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier); private type Blog_Service is new AWA.Modules.Module_Manager with null record; end AWA.Blogs.Services;
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- 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 ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package AWA.Blogs.Services is NAME : constant String := "Blog_Service"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Exception raised when a post cannot be found. Not_Found : exception; type Blog_Service is new AWA.Modules.Module_Manager with private; type Blog_Service_Access is access all Blog_Service'Class; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier); private type Blog_Service is new AWA.Modules.Module_Manager with null record; end AWA.Blogs.Services;
Use the Permissions.Definition generic package
Use the Permissions.Definition generic package
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c5aaf43af9925c189a0ea375e3f340c2f123584e
mat/src/events/mat-events-timelines.ads
mat/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.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 Start_Id : MAT.Events.Targets.Event_Id_Type := 0; Start_Time : MAT.Types.Target_Tick_Ref := 0; End_Id : MAT.Events.Targets.Event_Id_Type := 0; End_Time : MAT.Types.Target_Tick_Ref := 0; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 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; Into : in out Timeline_Info_Vector); 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.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 Start_Id : MAT.Events.Targets.Event_Id_Type := 0; Start_Time : MAT.Types.Target_Tick_Ref := 0; End_Id : MAT.Events.Targets.Event_Id_Type := 0; End_Time : MAT.Types.Target_Tick_Ref := 0; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 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; 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.Targets.Probe_Event_Type; Max : in Positive; List : in out MAT.Events.Targets.Target_Event_Vector); end MAT.Events.Timelines;
Declare the Find_Related procedure to find the related event from an known event
Declare the Find_Related procedure to find the related event from an known event
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
75c2cf14eaf7d9ec061f40a2a4f182328c3dd7ad
src/asf-requests.ads
src/asf-requests.ads
----------------------------------------------------------------------- -- asf.requests -- ASF Requests -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; with EL.Contexts; with Util.Locales; with Util.Beans.Objects.Maps; with Util.Streams.Buffered; with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Finalization; with ASF.Cookies; with ASF.Sessions; with ASF.Responses; with ASF.Principals; with ASF.Parts; with ASF.Routes; with ASF.Streams; -- The <b>ASF.Requests</b> package is an Ada implementation of -- the Java servlet request (JSR 315 3. The Request). package ASF.Requests is use Ada.Strings.Unbounded; type Quality_Type is digits 4 range 0.0 .. 1.0; -- Split an accept like header into multiple tokens and a quality value. -- Invoke the <b>Process</b> procedure for each token. Example: -- Accept-Language: de, en;q=0.7, jp, fr;q=0.8, ru -- The <b>Process</b> will be called for "de", "en" with quality 0.7, -- and "jp", "fr" with quality 0.8 and then "ru" with quality 1.0. procedure Split_Header (Header : in String; Process : access procedure (Item : in String; Quality : in Quality_Type)); -- ------------------------------ -- Request -- ------------------------------ -- The <b>Request</b> type describes a web request that a servlet can process. type Request is abstract new Ada.Finalization.Limited_Controlled with private; type Request_Access is access all Request'Class; -- Returns the value of the named attribute as an Object, or null if no attribute -- of the given name exists. -- -- Attributes can be set two ways. The servlet container may set attributes to make -- available custom information about a request. For example, for requests made -- using HTTPS, the attribute javax.servlet.request.X509Certificate can be used -- to retrieve information on the certificate of the client. Attributes can also -- be set programatically using setAttribute(String, Object). -- This allows information to be embedded into a request before -- a RequestDispatcher call. function Get_Attribute (Req : in Request; Name : in String) return EL.Objects.Object; -- Stores an attribute in this request. Attributes are reset between requests. -- This method is most often used in conjunction with RequestDispatcher. -- -- If the object passed in is null, the effect is the same as calling -- removeAttribute(java.lang.String). It is warned that when the request is -- dispatched from the servlet resides in a different web application by -- RequestDispatcher, the object set by this method may not be correctly -- retrieved in the caller servlet. procedure Set_Attribute (Req : in out Request; Name : in String; Value : in EL.Objects.Object); -- Stores a list of attributes in this request. procedure Set_Attributes (Req : in out Request; Attributes : in Util.Beans.Objects.Maps.Map); -- Removes an attribute from this request. This method is not generally needed -- as attributes only persist as long as the request is being handled. procedure Remove_Attribute (Req : in out Request; Name : in String); -- Iterate over the request attributes and executes the <b>Process</b> procedure. procedure Iterate_Attributes (Req : in Request; Process : not null access procedure (Name : in String; Value : in EL.Objects.Object)); -- Returns the name of the character encoding used in the body of this request. -- This method returns null if the request does not specify a character encoding function Get_Character_Encoding (Req : in Request) return String; -- Overrides the name of the character encoding used in the body of this request. -- This method must be called prior to reading request parameters or reading input -- using getReader(). Otherwise, it has no effect. procedure Set_Character_Encoding (Req : in out Request; Encoding : in String); -- Returns the length, in bytes, of the request body and made available by the -- input stream, or -1 if the length is not known. For HTTP servlets, -- same as the value of the CGI variable CONTENT_LENGTH. function Get_Content_Length (Req : in Request) return Integer; -- Returns the MIME type of the body of the request, or null if the type is -- not known. For HTTP servlets, same as the value of the CGI variable CONTENT_TYPE. function Get_Content_Type (Req : in Request) return String; -- Returns the value of a request parameter as a String, or null if the -- parameter does not exist. Request parameters are extra information sent with -- the request. For HTTP servlets, parameters are contained in the query string -- or posted form data. -- -- You should only use this method when you are sure the parameter has only one -- value. If the parameter might have more than one value, use -- Get_Parameter_Values(String). -- -- If you use this method with a multivalued parameter, the value returned is -- equal to the first value in the array returned by Get_Parameter_Values. -- -- If the parameter data was sent in the request body, such as occurs with -- an HTTP POST request, then reading the body directly via getInputStream() -- or getReader() can interfere with the execution of this method. -- function Get_Parameter (Req : in Request; Name : in String) return String is abstract; -- Returns an array of String objects containing all of the values the given -- request parameter has, or null if the parameter does not exist. -- -- If the parameter has a single value, the array has a length of 1. function Get_Parameter_Values (Req : in Request; Name : in String) return String; -- Iterate over the request parameters and executes the <b>Process</b> procedure. procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is abstract; -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. function Get_Protocol (Req : in Request) return String; -- Returns the name of the scheme used to make this request, for example, http, -- https, or ftp. Different schemes have different rules for constructing URLs, -- as noted in RFC 1738. function Get_Scheme (Req : in Request) return String; -- Returns the host name of the server to which the request was sent. -- It is the value of the part before ":" in the Host header value, if any, -- or the resolved server name, or the server IP address. function Get_Server_Name (Req : in Request) return String; -- Returns the port number to which the request was sent. It is the value of the -- part after ":" in the Host header value, if any, or the server port where the -- client connection was accepted on. function Get_Server_Port (Req : in Request) return Natural; -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. function Get_Remote_Addr (Req : in Request) return String; -- Returns the fully qualified name of the client or the last proxy that sent -- the request. If the engine cannot or chooses not to resolve the hostname -- (to improve performance), this method returns the dotted-string form of the -- IP address. For HTTP servlets, same as the value of the CGI variable REMOTE_HOST. function Get_Remote_Host (Req : in Request) return String; -- Returns the preferred Locale that the client will accept content in, based -- on the Accept-Language header. If the client request doesn't provide an -- Accept-Language header, this method returns the default locale for the server. function Get_Locale (Req : in Request) return Util.Locales.Locale; -- Returns an Enumeration of Locale objects indicating, in decreasing order -- starting with the preferred locale, the locales that are acceptable to the -- client based on the Accept-Language header. If the client request doesn't -- provide an Accept-Language header, this method returns an Enumeration containing -- one Locale, the default locale for the server. function Get_Locales (Req : in Request) return Util.Locales.Locale; -- From the <b>Accept-Language</b> request header, find the locales that are recognized -- by the client and execute the <b>Process</b> procedure with each locale and the -- associated quality value (ranging from 0.0 to 1.0). procedure Accept_Locales (Req : in Request; Process : access procedure (Item : in Util.Locales.Locale; Quality : in Quality_Type)); -- Returns a boolean indicating whether this request was made using a secure -- channel, such as HTTPS. function Is_Secure (Req : in Request) return Boolean; -- Returns the Internet Protocol (IP) source port of the client or last proxy -- that sent the request. function Get_Remote_Port (Req : in Request) return Natural; -- Returns the host name of the Internet Protocol (IP) interface on which -- the request was received. function Get_Local_Name (Req : in Request) return String; -- Returns the Internet Protocol (IP) address of the interface on which the -- request was received. function Get_Local_Addr (Req : in Request) return String; -- Returns the Internet Protocol (IP) port number of the interface on which -- the request was received. function Get_Local_Port (Req : in Request) return Natural; -- Returns the name of the authentication scheme used to protect the servlet. -- All servlet containers support basic, form and client certificate authentication, -- and may additionally support digest authentication. If the servlet is not -- authenticated null is returned. function Get_Auth_Type (Req : in Request) return String; -- Returns an array containing all of the Cookie objects the client sent with -- this request. This method returns null if no cookies were sent. function Get_Cookies (Req : in Request) return ASF.Cookies.Cookie_Array; -- Iterate over the request cookies and executes the <b>Process</b> procedure. procedure Iterate_Cookies (Req : in Request; Process : not null access procedure (Cookie : in ASF.Cookies.Cookie)); -- Returns the value of the specified request header as a long value that -- represents a Date object. Use this method with headers that contain dates, -- such as If-Modified-Since. -- -- The date is returned as the number of milliseconds since January 1, 1970 GMT. -- The header name is case insensitive. -- -- If the request did not have a header of the specified name, this method -- returns -1. If the header can't be converted to a date, the method throws -- an IllegalArgumentException. function Get_Date_Header (Req : in Request; Name : in String) return Ada.Calendar.Time; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. function Get_Header (Req : in Request; Name : in String) return String; -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. function Get_Headers (Req : in Request; Name : in String) return String; -- Returns the value of the specified request header as an int. If the request -- does not have a header of the specified name, this method returns -1. -- If the header cannot be converted to an integer, this method throws -- a NumberFormatException. -- -- The header name is case insensitive. function Get_Int_Header (Req : in Request; Name : in String) return Integer; -- Iterate over the request headers and executes the <b>Process</b> procedure. procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is abstract; -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. function Get_Method (Req : in Request) return String; -- Returns any extra path information associated with the URL the client sent when -- it made this request. The extra path information follows the servlet path but -- precedes the query string and will start with a "/" character. function Get_Path_Info (Req : in Request) return String; -- Get the request path that correspond to the servlet path and the path info. function Get_Path (Req : in Request) return String; -- Returns the portion of the request URI that indicates the context of the -- request. The context path always comes first in a request URI. The path -- starts with a "/" character but does not end with a "/" character. -- For servlets in the default (root) context, this method returns "". -- The container does not decode this string. function Get_Context_Path (Req : in Request) return String; -- Returns the query string that is contained in the request URL after the path. -- This method returns null if the URL does not have a query string. Same as the -- value of the CGI variable QUERY_STRING. function Get_Query_String (Req : in Request) return String; -- Returns the login of the user making this request, if the user has been -- authenticated, or null if the user has not been authenticated. Whether -- the user name is sent with each subsequent request depends on the browser -- and type of authentication. Same as the value of the CGI variable REMOTE_USER. function Get_Remote_User (Req : in Request) return String; -- Returns a Principal object containing the name of the current -- authenticated user. If the user has not been authenticated, the method returns null. function Get_User_Principal (Req : in Request) return ASF.Principals.Principal_Access; -- Returns the session ID specified by the client. This may not be the same as -- the ID of the current valid session for this request. If the client did not -- specify a session ID, this method returns null. function Get_Request_Session_Id (Req : in Request) return String; -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz function Get_Request_URI (Req : in Request) return String; -- Reconstructs the URL the client used to make the request. The returned URL -- contains a protocol, server name, port number, and server path, but it does -- not include query string parameters. -- -- If this request has been forwarded using RequestDispatcher.forward(Request, Response), -- the server path in the reconstructed URL must reflect the path used to -- obtain the RequestDispatcher, and not the server path specified by the client. -- -- Because this method returns a StringBuffer, not a string, you can modify the -- URL easily, for example, to append query parameters. -- -- This method is useful for creating redirect messages and for reporting errors. function Get_Request_URL (Req : in Request) return Ada.Strings.Unbounded.Unbounded_String; -- Returns the part of this request's URL that calls the servlet. This path starts -- with a "/" character and includes either the servlet name or a path to the -- servlet, but does not include any extra path information or a query string. -- Same as the value of the CGI variable SCRIPT_NAME. -- -- This method will return an empty string ("") if the servlet used to process -- this request was matched using the "/*" pattern. function Get_Servlet_Path (Req : in Request) return String; -- Returns the current HttpSession associated with this request or, if there -- is no current session and create is true, returns a new session. -- -- If create is false and the request has no valid HttpSession, this method -- returns null. -- -- To make sure the session is properly maintained, you must call this method -- before the response is committed. If the container is using cookies to maintain -- session integrity and is asked to create a new session when the response is -- committed, an IllegalStateException is thrown. function Get_Session (Req : in Request; Create : in Boolean := False) return ASF.Sessions.Session; -- Set the path info. The <tt>Path_Pos</tt> parameter indicates the optional starting -- position for the path info. When specified, the servlet path is built from the -- beginning of the path up to that path position. procedure Set_Path_Info (Req : in out Request; Path : in String; Path_Pos : in Natural := 0); -- Get the number of parts included in the request. function Get_Part_Count (Req : in Request) return Natural is abstract; -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is abstract; -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is abstract; -- Returns True if the request is an AJAX request. function Is_Ajax_Request (Req : in Request) return Boolean; -- Returns the absolute path of the resource identified by the given relative path. -- The resource is searched in a list of directories configured by the application. -- The path must begin with a "/" and is interpreted as relative to the current -- context root. -- -- This method allows the servlet container to make a resource available to -- servlets from any source. -- -- This method returns an empty string if the resource could not be localized. function Get_Resource (Req : in Request; Path : in String) return String; -- Returns the route object that is associated with the request. function Get_Route (Req : in Request) return ASF.Routes.Route_Type_Access; -- Inject the parameters that have been extracted from the path according -- to the selected route. The parameters are injected in the request attributes map. procedure Inject_Parameters (Req : in out Request; ELContext : in EL.Contexts.ELContext'Class); -- Get the path parameter value for the given parameter index. -- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist. function Get_Path_Parameter (Req : in Request; Index : in Positive) return String; -- Get the number of path parameters that were extracted for the route. function Get_Path_Parameter_Count (Req : in Request) return Natural; -- Get a buffer stream to read the request body. function Get_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access; -- Create the buffer stream instance to read the request body. function Create_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access is (null); -- Initialize the request object. overriding procedure Initialize (Req : in out Request); -- Finalize the request object. overriding procedure Finalize (Req : in out Request); private -- Make sure the cookies are loaded in the request object. procedure Load_Cookies (Req : in Request'Class); -- Get and check the request session function Has_Session (Req : in Request'Class) return Boolean; type Request_Data is record -- The session Session : ASF.Sessions.Session; -- Indicates whether the session object is known. Session_Initialized : Boolean := False; -- The response object associated with the request. Response : ASF.Responses.Response_Access; -- The request cookies. Cookies : ASF.Cookies.Cookie_Array_Access := null; -- The input stream. Stream : ASF.Streams.Input_Stream_Access; end record; type Request_Data_Access is access Request_Data; type Request is abstract new Ada.Finalization.Limited_Controlled with record Attributes : Util.Beans.Objects.Maps.Map_Bean; Info : Request_Data_Access := null; Context : access ASF.Routes.Route_Context_Type; end record; end ASF.Requests;
----------------------------------------------------------------------- -- asf-requests -- ASF Requests -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Requests; package ASF.Requests renames Servlet.Requests;
Package ASF.Requests moved to Servlet.Requests
Package ASF.Requests moved to Servlet.Requests
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1fae2abe6b374c4fb35265097d40b73ad1e1535f
src/core/texts/util-texts-builders.adb
src/core/texts/util-texts-builders.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Element_Type is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; procedure Inline_Append (Source : in out Builder) is B : Block_Access := Source.Current; Last : Natural; begin loop if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Process (B.Content (B.Last + 1 .. B.Len), Last); exit when Last > B.Len or Last <= B.Last; Source.Length := Source.Length + Last - B.Last; B.Last := Last; exit when Last < B.Len; end loop; end Inline_Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; procedure Inline_Iterate (Source : in Builder) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Inline_Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Get the element at the given position. -- ------------------------------ function Element (Source : in Builder; Position : in Positive) return Element_Type is begin if Position <= Source.First.Last then return Source.First.Content (Position); else declare Pos : Positive := Position - Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if Pos <= B.Last then return B.Content (Pos); end if; Pos := Pos - B.Last; B := B.Next_Block; end loop; end; end if; end Element; -- ------------------------------ -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. -- ------------------------------ function Find (Source : in Builder; Position : in Positive) return Natural is Result : Natural; begin if Position <= Source.First.Last then Result := Index (Source.First.Content (Position .. Source.First.Last)); if Result > 0 then return Result; end if; end if; declare Pos : Integer := Position - Source.First.Last; Offset : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin loop if B = null then return 0; end if; if Pos <= B.Last then Result := Index (B.Content (1 .. B.Last)); if Result > 0 then return Offset + Result; end if; end if; Pos := Pos - B.Last; Offset := Offset + B.Last; B := B.Next_Block; end loop; end; end Find; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
Add the generic Find function
Add the generic Find function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1a4f2b84b35c7468af7faa1c05c7c01f4cf243f3
src/core/texts/util-texts-builders.adb
src/core/texts/util-texts-builders.adb
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 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 Ada.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2016, 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.Unchecked_Deallocation; package body Util.Texts.Builders is -- ------------------------------ -- Get the length of the item builder. -- ------------------------------ function Length (Source : in Builder) return Natural is begin return Source.Length; end Length; -- ------------------------------ -- Get the capacity of the builder. -- ------------------------------ function Capacity (Source : in Builder) return Natural is B : constant Block_Access := Source.Current; begin return Source.Length + B.Len - B.Last; end Capacity; -- ------------------------------ -- Get the builder block size. -- ------------------------------ function Block_Size (Source : in Builder) return Positive is begin return Source.Block_Size; end Block_Size; -- ------------------------------ -- Set the block size for the allocation of next chunks. -- ------------------------------ procedure Set_Block_Size (Source : in out Builder; Size : in Positive) is begin Source.Block_Size := Size; end Set_Block_Size; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Input) is B : Block_Access := Source.Current; Start : Natural := New_Item'First; Last : constant Natural := New_Item'Last; begin while Start <= Last loop declare Space : Natural := B.Len - B.Last; Size : constant Natural := Last - Start + 1; begin if Space > Size then Space := Size; elsif Space = 0 then if Size > Source.Block_Size then B.Next_Block := new Block (Size); else B.Next_Block := new Block (Source.Block_Size); end if; B := B.Next_Block; Source.Current := B; if B.Len > Size then Space := Size; else Space := B.Len; end if; end if; B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1); Source.Length := Source.Length + Space; B.Last := B.Last + Space; Start := Start + Space; end; end loop; end Append; -- ------------------------------ -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. -- ------------------------------ procedure Append (Source : in out Builder; New_Item : in Element_Type) is B : Block_Access := Source.Current; begin if B.Len = B.Last then B.Next_Block := new Block (Source.Block_Size); B := B.Next_Block; Source.Current := B; end if; Source.Length := Source.Length + 1; B.Last := B.Last + 1; B.Content (B.Last) := New_Item; end Append; -- ------------------------------ -- Clear the source freeing any storage allocated for the buffer. -- ------------------------------ procedure Clear (Source : in out Builder) is procedure Free is new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access); Current, Next : Block_Access; begin Next := Source.First.Next_Block; while Next /= null loop Current := Next; Next := Current.Next_Block; Free (Current); end loop; Source.First.Next_Block := null; Source.First.Last := 0; Source.Current := Source.First'Unchecked_Access; Source.Length := 0; end Clear; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)) is begin if Source.First.Last > 0 then Process (Source.First.Content (1 .. Source.First.Last)); declare B : Block_Access := Source.First.Next_Block; begin while B /= null loop Process (B.Content (1 .. B.Last)); B := B.Next_Block; end loop; end; end if; end Iterate; -- ------------------------------ -- Return the content starting from the tail and up to <tt>Length</tt> items. -- ------------------------------ function Tail (Source : in Builder; Length : in Natural) return Input is Last : constant Natural := Source.Current.Last; begin if Last >= Length then return Source.Current.Content (Last - Length + 1 .. Last); elsif Length >= Source.Length then return To_Array (Source); else declare Result : Input (1 .. Length); Offset : Natural := Source.Length - Length; B : access constant Block := Source.First'Access; Src_Pos : Positive := 1; Dst_Pos : Positive := 1; Len : Natural; begin -- Skip the data moving to next blocks as needed. while Offset /= 0 loop if Offset < B.Last then Src_Pos := Offset + 1; Offset := 0; else Offset := Offset - B.Last + 1; B := B.Next_Block; end if; end loop; -- Copy what remains until we reach the length. while Dst_Pos <= Length loop Len := B.Last - Src_Pos + 1; Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last); Src_Pos := 1; Dst_Pos := Dst_Pos + Len; B := B.Next_Block; end loop; return Result; end; end if; end Tail; -- ------------------------------ -- Get the buffer content as an array. -- ------------------------------ function To_Array (Source : in Builder) return Input is Result : Input (1 .. Source.Length); begin if Source.First.Last > 0 then declare Pos : Positive := Source.First.Last; B : Block_Access := Source.First.Next_Block; begin Result (1 .. Pos) := Source.First.Content (1 .. Pos); while B /= null loop Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last); Pos := Pos + B.Last; B := B.Next_Block; end loop; end; end if; return Result; end To_Array; -- ------------------------------ -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. -- ------------------------------ procedure Get (Source : in Builder) is begin if Source.Length < Source.First.Len then Process (Source.First.Content (1 .. Source.Length)); else declare Content : constant Input := To_Array (Source); begin Process (Content); end; end if; end Get; -- ------------------------------ -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream -- ------------------------------ procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List) is C : Element_Type; Old_Pos : Natural; N : Natural := 0; Pos : Natural := Message'First; First : Natural := Pos; begin -- Replace {N} with arg1, arg2, arg3 or ? while Pos <= Message'Last loop C := Message (Pos); if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; N := 0; Pos := Pos + 1; C := Message (Pos); -- Handle {} replacement to emit the current argument and advance argument position. if Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Pos - 2; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; N := N + 1; else N := 0; Old_Pos := Pos - 1; loop if Element_Type'Pos (C) >= Character'Pos ('0') and Element_Type'Pos (C) <= Character'Pos ('9') then N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0')); Pos := Pos + 1; if Pos > Message'Last then First := Old_Pos; exit; end if; elsif Element_Type'Pos (C) = Character'Pos ('}') then Pos := Pos + 1; if N >= Arguments'Length then First := Old_Pos; else Append (Into, Arguments (N + Arguments'First)); First := Pos; end if; exit; else First := Old_Pos; exit; end if; C := Message (Pos); end loop; end if; else Pos := Pos + 1; end if; end loop; if First /= Pos then Append (Into, Message (First .. Pos - 1)); end if; end Format; -- ------------------------------ -- Setup the builder. -- ------------------------------ overriding procedure Initialize (Source : in out Builder) is begin Source.Current := Source.First'Unchecked_Access; end Initialize; -- ------------------------------ -- Finalize the builder releasing the storage. -- ------------------------------ overriding procedure Finalize (Source : in out Builder) is begin Clear (Source); end Finalize; end Util.Texts.Builders;
Implement the generic Format procedure (implementation taken from the Util.Tests.Formats package and Util.Log.Loggers.Format procedure)
Implement the generic Format procedure (implementation taken from the Util.Tests.Formats package and Util.Log.Loggers.Format procedure)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
96b69cfdc48e8206e56f17c66c312d8a53b4741d
awa/src/awa-applications.ads
awa/src/awa-applications.ads
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with ADO.Sessions.Factory; with AWA.Modules; with AWA.Events; with AWA.Events.Services; package AWA.Applications is -- Directories where the configuration files are searched. package P_Module_Dir is new ASF.Applications.Main.Configs.Parameter ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); -- A list of configuration files separated by ';'. These files are searched in -- 'app.modules.dir' and loaded in the order specified. package P_Config_File is new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml"); -- Module manager -- -- The <b>Module_Manager</b> represents the root of the logic manager type Application is new ASF.Applications.Main.Application with private; type Application_Access is access all Application'Class; -- Initialize the application overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config); -- 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 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); -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. procedure Load_Configuration (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. procedure Initialize_Modules (App : in out Application); -- Start the application. This is called by the server container when the server is started. overriding procedure Start (App : in out Application); -- Register the module in the application procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := ""); -- Get the database connection for reading function Get_Session (App : Application) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session; -- Register the module in the application procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := ""); -- Find the module with the given name function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access; -- Send the event in the application event queues. procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class); -- Execute the <tt>Process</tt> procedure with the event manager used by the application. procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)); -- Get the current application from the servlet context or service context. function Current return Application_Access; private -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class); type Application is new ASF.Applications.Main.Application with record DB_Factory : ADO.Sessions.Factory.Session_Factory; Modules : aliased AWA.Modules.Module_Registry; Events : aliased AWA.Events.Services.Event_Manager; end record; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.IO; with ASF.Applications.Main; with ASF.Applications.Main.Configs; with ADO.Sessions.Factory; with AWA.Modules; with AWA.Events; with AWA.Events.Services; package AWA.Applications is -- Directories where the configuration files are searched. package P_Module_Dir is new ASF.Applications.Main.Configs.Parameter ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); -- A list of configuration files separated by ';'. These files are searched in -- 'app.modules.dir' and loaded in the order specified before the application modules. package P_Config_File is new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml"); -- A list of configuration files separated by ';'. These files are searched in -- 'app.modules.dir' and loaded in the order specified after all the application modules -- are initialized. package P_Plugin_Config_File is new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", ""); -- Module manager -- -- The <b>Module_Manager</b> represents the root of the logic manager type Application is new ASF.Applications.Main.Application with private; type Application_Access is access all Application'Class; -- Initialize the application overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config); -- 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 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); -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. procedure Load_Configuration (App : in out Application; Files : in String); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. procedure Initialize_Modules (App : in out Application); -- Start the application. This is called by the server container when the server is started. overriding procedure Start (App : in out Application); -- Register the module in the application procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := ""); -- Get the database connection for reading function Get_Session (App : Application) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session; -- Register the module in the application procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := ""); -- Find the module with the given name function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access; -- Send the event in the application event queues. procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class); -- Execute the <tt>Process</tt> procedure with the event manager used by the application. procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)); -- Get the current application from the servlet context or service context. function Current return Application_Access; private -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class); type Application is new ASF.Applications.Main.Application with record DB_Factory : ADO.Sessions.Factory.Session_Factory; Modules : aliased AWA.Modules.Module_Registry; Events : aliased AWA.Events.Services.Event_Manager; end record; end AWA.Applications;
Change Load_Configuration to allow reading a custom configuration file New configuration property to define a configuration file for plugins
Change Load_Configuration to allow reading a custom configuration file New configuration property to define a configuration file for plugins
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0c58ace73da6525206f7e544e3f05140e1384373
src/ado-schemas.ads
src/ado-schemas.ads
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Containers; with Util.Strings; package ADO.Schemas is type Member_Names is array (Natural range <>) of Util.Strings.Name_Access; type Class_Mapping (Count : Natural) is tagged record Table : Util.Strings.Name_Access; -- Name : Natural := 0; Members : Member_Names (1 .. Count); end record; type Class_Mapping_Access is access constant Class_Mapping'Class; -- Get the hash value associated with the class mapping. function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type; -- Get the Ada type mapping for the column type Column_Type is ( T_UNKNOWN, -- Boolean column T_BOOLEAN, T_TINYINT, T_SMALLINT, T_INTEGER, T_LONG_INTEGER, T_FLOAT, T_DOUBLE, T_DECIMAL, T_ENUM, T_SET, T_TIME, T_YEAR, T_DATE, T_DATE_TIME, T_TIMESTAMP, T_CHAR, T_VARCHAR, T_BLOB, T_NULL ); -- ------------------------------ -- Column Representation -- ------------------------------ -- Describes a column in a table. type Column_Definition is private; -- Get the column name function Get_Name (Column : Column_Definition) return String; -- Get the column type function Get_Type (Column : Column_Definition) return Column_Type; -- Get the default column value function Get_Default (Column : Column_Definition) return String; -- Get the column collation (for string based columns) function Get_Collation (Column : Column_Definition) return String; -- Check whether the column can be null function Is_Null (Column : Column_Definition) return Boolean; -- Check whether the column is an unsigned number function Is_Unsigned (Column : Column_Definition) return Boolean; -- Returns true if the column can hold a binary string function Is_Binary (Column : Column_Definition) return Boolean; -- Get the column length function Get_Size (Column : Column_Definition) return Natural; -- ------------------------------ -- Column iterator -- ------------------------------ type Column_Cursor is private; -- Returns true if the iterator contains more column function Has_Element (Cursor : Column_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Column_Cursor); -- Get the current column definition function Element (Cursor : Column_Cursor) return Column_Definition; -- ------------------------------ -- Table Representation -- ------------------------------ -- Describes a table in the database. The table contains a list -- of columns described by Column_Definition. type Table_Definition is private; -- Get the table name function Get_Name (Table : Table_Definition) return String; -- Get the column iterator function Get_Columns (Table : Table_Definition) return Column_Cursor; -- Find the column having the given name function Find_Column (Table : Table_Definition; Name : String) return Column_Definition; -- ------------------------------ -- Table iterator -- ------------------------------ type Table_Cursor is private; -- Returns true if the iterator contains more tables function Has_Element (Cursor : Table_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Table_Cursor); -- Get the current table definition function Element (Cursor : Table_Cursor) return Table_Definition; -- ------------------------------ -- Database Schema -- ------------------------------ type Schema_Definition is limited private; -- Find a table knowing its name function Find_Table (Schema : Schema_Definition; Name : String) return Table_Definition; function Get_Tables (Schema : Schema_Definition) return Table_Cursor; private use Ada.Strings.Unbounded; type Column; type Column_Definition is access all Column; type Table; type Table_Definition is access all Table; type Schema; type Schema_Access is access all Schema; type Schema_Definition is new Ada.Finalization.Limited_Controlled with record Schema : Schema_Access; end record; procedure Finalize (Schema : in out Schema_Definition); type Column_Cursor is record Current : Column_Definition; end record; type Table_Cursor is record Current : Table_Definition; end record; type Column is record Next_Column : Column_Definition; Table : Table_Definition; Name : Unbounded_String; Default : Unbounded_String; Collation : Unbounded_String; Col_Type : Column_Type := T_VARCHAR; Size : Natural := 0; Is_Null : Boolean := False; Is_Binary : Boolean := False; Is_Unsigned : Boolean := False; end record; type Table is record Name : Unbounded_String; First_Column : Column_Definition; Next_Table : Table_Definition; end record; type Schema is record -- Tables : Table_Definition; First_Table : Table_Definition; end record; end ADO.Schemas;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Containers; with Util.Strings; package ADO.Schemas is type Member_Names is array (Natural range <>) of Util.Strings.Name_Access; type Class_Mapping (Count : Natural) is tagged record Table : Util.Strings.Name_Access; Members : Member_Names (1 .. Count); end record; type Class_Mapping_Access is access constant Class_Mapping'Class; -- Get the hash value associated with the class mapping. function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type; -- Get the Ada type mapping for the column type Column_Type is ( T_UNKNOWN, -- Boolean column T_BOOLEAN, T_TINYINT, T_SMALLINT, T_INTEGER, T_LONG_INTEGER, T_FLOAT, T_DOUBLE, T_DECIMAL, T_ENUM, T_SET, T_TIME, T_YEAR, T_DATE, T_DATE_TIME, T_TIMESTAMP, T_CHAR, T_VARCHAR, T_BLOB, T_NULL ); -- ------------------------------ -- Column Representation -- ------------------------------ -- Describes a column in a table. type Column_Definition is private; -- Get the column name function Get_Name (Column : Column_Definition) return String; -- Get the column type function Get_Type (Column : Column_Definition) return Column_Type; -- Get the default column value function Get_Default (Column : Column_Definition) return String; -- Get the column collation (for string based columns) function Get_Collation (Column : Column_Definition) return String; -- Check whether the column can be null function Is_Null (Column : Column_Definition) return Boolean; -- Check whether the column is an unsigned number function Is_Unsigned (Column : Column_Definition) return Boolean; -- Returns true if the column can hold a binary string function Is_Binary (Column : Column_Definition) return Boolean; -- Returns true if the column is a primary key. function Is_Primary (Column : Column_Definition) return Boolean; -- Get the column length function Get_Size (Column : Column_Definition) return Natural; -- ------------------------------ -- Column iterator -- ------------------------------ type Column_Cursor is private; -- Returns true if the iterator contains more column function Has_Element (Cursor : Column_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Column_Cursor); -- Get the current column definition function Element (Cursor : Column_Cursor) return Column_Definition; -- ------------------------------ -- Table Representation -- ------------------------------ -- Describes a table in the database. The table contains a list -- of columns described by Column_Definition. type Table_Definition is private; -- Get the table name function Get_Name (Table : Table_Definition) return String; -- Get the column iterator function Get_Columns (Table : Table_Definition) return Column_Cursor; -- Find the column having the given name function Find_Column (Table : Table_Definition; Name : String) return Column_Definition; -- ------------------------------ -- Table iterator -- ------------------------------ type Table_Cursor is private; -- Returns true if the iterator contains more tables function Has_Element (Cursor : Table_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Table_Cursor); -- Get the current table definition function Element (Cursor : Table_Cursor) return Table_Definition; -- ------------------------------ -- Database Schema -- ------------------------------ type Schema_Definition is limited private; -- Find a table knowing its name function Find_Table (Schema : Schema_Definition; Name : String) return Table_Definition; function Get_Tables (Schema : Schema_Definition) return Table_Cursor; private use Ada.Strings.Unbounded; type Column; type Column_Definition is access all Column; type Table; type Table_Definition is access all Table; type Schema; type Schema_Access is access all Schema; type Schema_Definition is new Ada.Finalization.Limited_Controlled with record Schema : Schema_Access; end record; procedure Finalize (Schema : in out Schema_Definition); type Column_Cursor is record Current : Column_Definition; end record; type Table_Cursor is record Current : Table_Definition; end record; type Column is record Next_Column : Column_Definition; Table : Table_Definition; Name : Unbounded_String; Default : Unbounded_String; Collation : Unbounded_String; Col_Type : Column_Type := T_VARCHAR; Size : Natural := 0; Is_Null : Boolean := False; Is_Binary : Boolean := False; Is_Unsigned : Boolean := False; Is_Primary : Boolean := False; end record; type Table is record Name : Unbounded_String; First_Column : Column_Definition; Next_Table : Table_Definition; end record; type Schema is record -- Tables : Table_Definition; First_Table : Table_Definition; end record; end ADO.Schemas;
Declare the Is_Primary function.
Declare the Is_Primary function.
Ada
apache-2.0
stcarrez/ada-ado
fe097106654781983506cc114f7bfb92e9ce88fd
mat/src/gtk/mat-callbacks.ads
mat/src/gtk/mat-callbacks.ads
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gtkada.Builder; with MAT.Targets.Gtkmat; package MAT.Callbacks is -- Initialize and register the callbacks. procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access; Builder : in Gtkada.Builder.Gtkada_Builder); -- Callback executed when the "quit" action is executed from the menu. procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "about" action is executed from the menu. procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "close-about" action is executed from the about box. procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "cmd-sizes" action is executed from the "Sizes" action. procedure On_Btn_Sizes (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); end MAT.Callbacks;
----------------------------------------------------------------------- -- mat-callbacks - Callbacks for Gtk -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gtkada.Builder; with MAT.Targets.Gtkmat; package MAT.Callbacks is -- Initialize and register the callbacks. procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access; Builder : in Gtkada.Builder.Gtkada_Builder); -- Callback executed when the "quit" action is executed from the menu. procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "about" action is executed from the menu. procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "close-about" action is executed from the about box. procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "cmd-sizes" action is executed from the "Sizes" action. procedure On_Btn_Sizes (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); -- Callback executed when the "cmd-threads" action is executed from the "Threads" action. procedure On_Btn_Threads (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class); end MAT.Callbacks;
Declare the On_Btn_Threads procedure
Declare the On_Btn_Threads procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7e1b7e89bb02af8422f5e1f65cbed5512494d466
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add the Is_Auditable member to the Column_Definition type to identify the columns that need audit support (represented by the <<Auditable>> stereotype)
Add the Is_Auditable member to the Column_Definition type to identify the columns that need audit support (represented by the <<Auditable>> stereotype)
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
555d0b44e3eb7311d2ec846c69e6ef8820ef5c6f
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and F.Next /= Frame loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Frame.Next; end if; end if; Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- ------------------------------ -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. -- ------------------------------ procedure Split (F : in out Frame_Type; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Type := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; -- ------------------------------ -- 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 Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Current : Frame_Type := Frame; Child : Frame_Type; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); procedure Split (F : in out Frame_Type; Pos : in Positive); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and then F.Next /= Frame loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Frame.Next; end if; end if; Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- ------------------------------ -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. -- ------------------------------ procedure Split (F : in out Frame_Type; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Type := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; -- ------------------------------ -- 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 Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Current : Frame_Type := Frame; Child : Frame_Type; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type is Child : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural) is Current : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search : while Pos <= Pc'Last loop declare Addr : constant Target_Addr := Pc (Pos); Child : Frame_Type := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
Refactor the Find operation
Refactor the Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1794ca85e096de22c3b03cff62d26a3765a77a14
src/wiki-documents.ads
src/wiki-documents.ads
----------------------------------------------------------------------- -- wiki-documents -- Wiki document -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Attributes; with Wiki.Nodes; package Wiki.Documents is pragma Preelaborate; -- ------------------------------ -- A Wiki Document -- ------------------------------ type Document is tagged private; -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List); -- Pop the HTML tag. procedure Pop_Node (From : in out Document; Tag : in Html_Tag); -- 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); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Wiki.Nodes.Node_Type)); private -- Append a node to the document. procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access); type Document is tagged record Nodes : Wiki.Nodes.Node_List_Ref; Current : Wiki.Nodes.Node_Type_Access; end record; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-documents -- Wiki document -- Copyright (C) 2011, 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.Strings; with Wiki.Attributes; with Wiki.Nodes; package Wiki.Documents is pragma Preelaborate; -- ------------------------------ -- A Wiki Document -- ------------------------------ type Document is tagged private; -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List); -- Pop the HTML tag. procedure Pop_Node (From : in out Document; Tag : in Html_Tag); -- 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); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Wiki.Nodes.Node_Type)); -- Get the table of content node associated with the document. procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref); -- Get the table of content node associated with the document. function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref; private -- Append a node to the document. procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access); type Document is tagged record Nodes : Wiki.Nodes.Node_List_Ref; TOC : Wiki.Nodes.Node_List_Ref; Current : Wiki.Nodes.Node_Type_Access; end record; end Wiki.Documents;
Declare the Get_TOC procedure and function
Declare the Get_TOC procedure and function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a3204ec78e2cf1276f2305e3cc7e172e8d82b07c
src/wiki-helpers.adb
src/wiki-helpers.adb
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; package body Wiki.Helpers is -- ------------------------------ -- Returns True if the character is a space or tab. -- ------------------------------ function Is_Space (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT; end Is_Space; -- ------------------------------ -- Returns True if the character is a space, tab or a newline. -- ------------------------------ function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Space_Or_Newline; -- ------------------------------ -- Returns True if the character is a line terminator. -- ------------------------------ function Is_Newline (C : in Wiki.Strings.WChar) return Boolean is begin return Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C); end Is_Newline; -- ------------------------------ -- Returns True if the text is a valid URL -- ------------------------------ function Is_Url (Text : in Wiki.Strings.WString) return Boolean is begin if Text'Length <= 9 then return False; else return Text (Text'First .. Text'First + 6) = "http://" or Text (Text'First .. Text'First + 7) = "https://"; end if; end Is_Url; -- ------------------------------ -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. -- ------------------------------ function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean is S : constant Wiki.Strings.WString := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext); begin return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg"; end Is_Image_Extension; -- ------------------------------ -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. -- ------------------------------ function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean is begin if No_End_Tag (Current_Tag) then return True; elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then return True; else case Current_Tag is when DT_TAG | DD_TAG => return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG; when TD_TAG => return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG; when TR_TAG => return False; when others => return False; end case; end if; end Need_Close; -- ------------------------------ -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> -- ------------------------------ procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural) is Pos : Natural; Last : Natural; begin if Dimension = "original" then Width := Natural'Last; Height := Natural'Last; elsif Dimension = "default" or Dimension = "upright" then Width := 800; Height := 0; else Pos := Wiki.Strings.Index (Dimension, "x"); Last := Wiki.Strings.Index (Dimension, "px"); if Pos > Dimension'First and Last + 1 /= Pos then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Pos - 1)); elsif Last > 0 then Width := Natural'Wide_Wide_Value (Dimension (Dimension'First .. Last - 1)); else Width := 0; end if; if Pos < Dimension'Last then Height := Natural'Wide_Wide_Value (Dimension (Pos + 1 .. Last - 1)); else Height := 0; end if; end if; exception when Constraint_Error => Width := 0; Height := 0; end Get_Sizes; end Wiki.Helpers;
Implement Get_Sizes using the MediaWiki syntax
Implement Get_Sizes using the MediaWiki syntax
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
370b969f6a4361f6d5804f4a236c8ebb2d118bb8
src/base/os-windows/util-systems-os.ads
src/base/os-windows/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; type Process_Identifier is new Integer; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := 16#fffffff6#; STD_OUTPUT_HANDLE : constant DWORD := 16#fffffff5#; STD_ERROR_HANDLE : constant DWORD := 16#fffffff4#; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; subtype LPVOID is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lstat (Path : in String; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; function Replace_File (Replaced_File : in LPCTSTR; Replacement_File : in LPCTSTR; Backup_File : in LPCTSTR; Replace_Flags : in DWORD; Exclude : in LPCTSTR; Reserved : in LPCTSTR) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReplaceFileW"; function Move_File (Existing_File : in LPCTSTR; New_File : in LPCTSTR; Flags : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "MoveFileExW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => "unlink"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; with Util.Systems.Constants; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; type Process_Identifier is new Integer; function Get_Last_Error return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; function Errno return Integer with Import => True, Convention => Stdcall, Link_Name => "GetLastError"; -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD with Import => True, Convention => Stdcall, Link_Name => "WaitForSingleObject"; type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Interfaces.C.int := 0; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := 16#fffffff6#; STD_OUTPUT_HANDLE : constant DWORD := 16#fffffff5#; STD_ERROR_HANDLE : constant DWORD := 16#fffffff4#; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; function Get_Std_Handle (Kind : in DWORD) return File_Type with Import => True, Convention => Stdcall, Link_Name => "GetStdHandle"; function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function STDOUT_FILENO return File_Type is (Get_Std_Handle (STD_OUTPUT_HANDLE)); function STDERR_FILENO return File_Type is (Get_Std_Handle (STD_ERROR_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CloseHandle"; function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "DuplicateHandle"; function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReadFile"; function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL with Import => True, Convention => Stdcall, Link_Name => "WriteFile"; function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "CreatePipe"; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; subtype LPVOID is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type FileTime is record dwLowDateTime : DWORD; dwHighDateTime : DWORD; end record; type LPFILETIME is access all FileTime; function To_Time (Time : in FileTime) return Util.Systems.Types.Time_Type; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE with Import => True, Convention => Stdcall, Link_Name => "GetCurrentProcess"; function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetExitCodeProcess"; function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handles : in BOOL; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer with Import => True, Convention => Stdcall, Link_Name => "CreateProcessW"; -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer with Import => True, Convention => Stdcall, Link_Name => "TerminateProcess"; function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; function Sys_Lstat (Path : in String; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => Stdcall, Link_Name => "_stat64"; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE with Import => True, Convention => Stdcall, Link_Name => "CreateFileW"; function Replace_File (Replaced_File : in LPCTSTR; Replacement_File : in LPCTSTR; Backup_File : in LPCTSTR; Replace_Flags : in DWORD; Exclude : in LPCTSTR; Reserved : in LPCTSTR) return BOOL with Import => True, Convention => Stdcall, Link_Name => "ReplaceFileW"; function Move_File (Existing_File : in LPCTSTR; New_File : in LPCTSTR; Flags : in DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "MoveFileExW"; function Get_Full_Pathname (Path : in LPCTSTR; Length : in DWORD; Buffer : in LPCTSTR; Ptr : in LPCSTR) return DWORD with Import => True, Convention => Stdcall, Link_Name => "GetFullPathNameW"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => Stdcall, Link_Name => "_chmod"; function Sys_Realpath (S : in Ptr; R : in Ptr) return Ptr; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => Stdcall, Link_Name => "strerror"; function Sys_GetHandleInformation (Fd : in HANDLE; Flags : access DWORD) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetHandleInformation"; type Wchar_Ptr is access all Interfaces.C.wchar_array; function To_WSTR (Value : in String) return Wchar_Ptr; procedure Free is new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array, Name => Wchar_Ptr); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in String; Newpath : in String) return Integer; function Sys_Unlink (Path : in String) return Integer with Import => True, Convention => C, Link_Name => "unlink"; type DIR is new System.Address; Null_Dir : constant DIR := DIR (System.Null_Address); -- Equivalent to Posix opendir (3) but handles some portability issues. -- We could use opendir, readdir_r and closedir but the __gnat_* alternative -- solves function Opendir (Directory : in String) return DIR with Import, External_Name => "__gnat_opendir", Convention => C; function Readdir (Directory : in DIR; Buffer : in System.Address; Last : not null access Integer) return System.Address with Import, External_Name => "__gnat_readdir", Convention => C; function Closedir (Directory : in DIR) return Integer with Import, External_Name => "__gnat_closedir", Convention => C; private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Declare Sys_Realpath and Get_Full_Pathname
Declare Sys_Realpath and Get_Full_Pathname
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f40a26a98a981079c81098d622e5a657a4f76a00
mat/src/mat-targets.adb
mat/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Util.Strings; with Util.Log.Loggers; with MAT.Targets.Readers; package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Targets.Readers.Initialize (Target => Target, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Ada.Strings.Unbounded.To_String (Path)); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with GNAT.Command_Line; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Readers; package body MAT.Targets is -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Targets.Readers.Initialize (Target => Target, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); if Target.Options.Load_Symbols then MAT.Commands.Symbol_Command (Target, Path_String); end if; end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; end MAT.Targets;
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9d1fb680dfbb505d5630c980275ce3cda59fc47a
samples/rest/monitor.ads
samples/rest/monitor.ads
----------------------------------------------------------------------- -- monitor - A simple monitor API -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with ASF.Rest.Definition; package Monitor is type Mon is new Natural; -- Get values of the monitor. procedure Get_Values (D : in out Mon; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- PUT /mon/:id procedure Put_Value (D : in out Mon; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); package Mon_API is new ASF.Rest.Definition (Object_Type => Mon, URI => "/api/monitor"); private -- Declare each REST API with a relative URI from Mon_API definition. -- GET /api/monitor/:id package Mon_Get_Values is new Mon_API.Definition (Handler => Get_Values'Access, Method => ASF.Rest.GET, Pattern => ":id", Permission => 0); -- PUT /api/monitor/:id package Mon_Put_Value is new Mon_API.Definition (Handler => Put_Value'Access, Method => ASF.Rest.PUT, Pattern => ":id", Permission => 0); MAX_VALUES : constant Natural := 1000; MAX_MONITOR : constant Natural := 10; type Value_Array is array (Natural range <>) of Natural; protected type Monitor_Data is procedure Put (Value : in Natural); procedure Put (Value : in Natural; Slot : in Natural); function Get_Values return Value_Array; private Values : Value_Array (1 .. MAX_VALUES) := (others => 0); Value_Count : Natural := 0; Pos : Natural := 1; Slot_Size : Duration := 10.0; Slot_Start : Ada.Calendar.Time := Ada.Calendar.Clock; end Monitor_Data; end Monitor;
----------------------------------------------------------------------- -- monitor - A simple monitor API -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with ASF.Rest.Operation; package Monitor is -- Get values of the monitor. procedure Get_Values (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- PUT /mon/:id procedure Put_Value (Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- Declare each REST API with a relative URI from Mon_API definition. -- GET /api/monitor/:id package API_Get_Values is new ASF.Rest.Operation (Handler => Get_Values'Access, Method => ASF.Rest.GET, URI => "/mon/:id"); -- PUT /api/monitor/:id package API_Put_Value is new ASF.Rest.Operation (Handler => Put_Value'Access, Method => ASF.Rest.PUT, URI => "/mon/:id"); private MAX_VALUES : constant Natural := 1000; MAX_MONITOR : constant Natural := 10; type Value_Array is array (Natural range <>) of Natural; protected type Monitor_Data is procedure Put (Value : in Natural); procedure Put (Value : in Natural; Slot : in Natural); function Get_Values return Value_Array; private Values : Value_Array (1 .. MAX_VALUES) := (others => 0); Value_Count : Natural := 0; Pos : Natural := 1; Slot_Size : Duration := 10.0; Slot_Start : Ada.Calendar.Time := Ada.Calendar.Clock; end Monitor_Data; end Monitor;
Update the REST API declaration
Update the REST API declaration
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
03800482eeb72b165f1b390883a06578a5453bda
testutil/util-tests-reporter.adb
testutil/util-tests-reporter.adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . R E P O R T E R . X M L -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2009, AdaCore -- -- -- -- 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 2, 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 COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with AUnit.Time_Measure; with Util.Strings; -- Very simple reporter to console package body Util.Tests.Reporter is use AUnit.Test_Results; use AUnit.Time_Measure; use type AUnit.Message_String; use Ada.Text_IO; procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List); -- List failed assertions -- procedure Put_Measure is new Gen_Put_Measure; -- Output elapsed time procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result); -- Report a single assertion failure or unexpected exception procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer); procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer) is begin Ada.Text_IO.Put (File, Util.Strings.Image (I)); end Put; ---------------------- -- Dump_Result_List -- ---------------------- procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List) is use Result_Lists; C : Cursor := First (L); begin -- Note: can't use Iterate because it violates restriction -- No_Implicit_Dynamic_Code while Has_Element (C) loop Report_Test (File, Element (C)); Next (C); end loop; end Dump_Result_List; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; R : in out Result'Class) is Output : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => To_String (Engine.File)); Engine.Report (Output, R); Ada.Text_IO.Close (Output); end Report; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; File : in out Ada.Text_IO.File_Type; R : in out Result'Class) is pragma Unreferenced (Engine); procedure Put (I : in Integer); procedure Put (S : in String); T : AUnit_Duration; procedure Put (I : in Integer) is begin Ada.Text_IO.Put (File, Integer'Image (I)); end Put; procedure Put (S : in String) is begin Put (File, S); end Put; procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure; begin Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>"); Put (File, "<TestRun"); if Elapsed (R) /= AUnit.Time_Measure.Null_Time then T := Get_Measure (Elapsed (R)); Put (File, " elapsed='"); Put_Measure (T); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Put_Line (File, " <Statistics>"); Put (File, " <Tests>"); Put (File, Integer (Test_Count (R))); Put_Line (File, "</Tests>"); Put (File, " <FailuresTotal>"); Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R))); Put_Line (File, "</FailuresTotal>"); Put (File, " <Failures>"); Put (File, Integer (Failure_Count (R))); Put_Line (File, "</Failures>"); Put (File, " <Errors>"); Put (File, Integer (Error_Count (R))); Put_Line (File, "</Errors>"); Put_Line (File, " </Statistics>"); declare S : Result_Lists.List; begin Put_Line (File, " <SuccessfulTests>"); Successes (R, S); Dump_Result_List (File, S); Put_Line (File, " </SuccessfulTests>"); end; Put_Line (File, " <FailedTests>"); declare F : Result_Lists.List; begin Failures (R, F); Dump_Result_List (File, F); end; declare E : Result_Lists.List; begin Errors (R, E); Dump_Result_List (File, E); end; Put_Line (File, " </FailedTests>"); Put_Line (File, "</TestRun>"); end Report; ------------------ -- Report_Error -- ------------------ procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result) is procedure Put (I : in Integer); procedure Put (S : in String); Is_Assert : Boolean; T : AUnit_Duration; procedure Put (I : in Integer) is begin Put (File, I); end Put; procedure Put (S : in String) is begin Put (File, S); end Put; procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure; begin Put (File, " <Test"); if Test.Elapsed /= AUnit.Time_Measure.Null_Time then T := Get_Measure (Test.Elapsed); Put (File, " elapsed='"); Put_Measure (T); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Put (File, " <Name>"); Put (File, Test.Test_Name.all); if Test.Routine_Name /= null then Put (File, " : "); Put (File, Test.Routine_Name.all); end if; Put_Line (File, "</Name>"); if Test.Failure /= null or else Test.Error /= null then if Test.Failure /= null then Is_Assert := True; else Is_Assert := False; end if; Put (File, " <FailureType>"); if Is_Assert then Put (File, "Assertion"); else Put (File, "Error"); end if; Put_Line (File, "</FailureType>"); Put (File, " <Message>"); if Is_Assert then Put (File, Test.Failure.Message.all); else Put (File, Test.Error.Exception_Name.all); end if; Put_Line (File, "</Message>"); if Is_Assert then Put_Line (File, " <Location>"); Put (File, " <File>"); Put (File, Test.Failure.Source_Name.all); Put_Line (File, "</File>"); Put (File, " <Line>"); Put (File, Test.Failure.Line); Put_Line (File, "</Line>"); Put_Line (File, " </Location>"); else Put_Line (File, " <Exception>"); Put (File, " <Message>"); Put (File, Test.Error.Exception_Name.all); Put_Line (File, "</Message>"); if Test.Error.Exception_Message /= null then Put (File, " <Information>"); Put (File, Test.Error.Exception_Message.all); Put_Line (File, "</Information>"); end if; if Test.Error.Traceback /= null then Put (File, " <Traceback>"); Put (File, Test.Error.Traceback.all); Put_Line (File, "</Traceback>"); end if; Put_Line (File, " </Exception>"); end if; end if; Put_Line (File, " </Test>"); end Report_Test; end Util.Tests.Reporter;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . R E P O R T E R . X M L -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2009, AdaCore -- -- -- -- 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 2, 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 COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with AUnit.Time_Measure; with Util.Strings; -- Very simple reporter to console package body Util.Tests.Reporter is use AUnit.Test_Results; use AUnit.Time_Measure; use type AUnit.Message_String; use Ada.Text_IO; procedure Print_Summary (R : in out Result'Class); procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List); -- List failed assertions -- procedure Put_Measure is new Gen_Put_Measure; -- Output elapsed time procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result); -- Report a single assertion failure or unexpected exception procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer); procedure Put (File : in Ada.Text_IO.File_Type; I : in Integer) is begin Ada.Text_IO.Put (File, Util.Strings.Image (I)); end Put; ---------------------- -- Dump_Result_List -- ---------------------- procedure Dump_Result_List (File : in Ada.Text_IO.File_Type; L : in Result_Lists.List) is use Result_Lists; C : Cursor := First (L); begin -- Note: can't use Iterate because it violates restriction -- No_Implicit_Dynamic_Code while Has_Element (C) loop Report_Test (File, Element (C)); Next (C); end loop; end Dump_Result_List; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; R : in out Result'Class) is Output : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => To_String (Engine.File)); Engine.Report (Output, R); Ada.Text_IO.Close (Output); end Report; procedure Print_Summary (R : in out Result'Class) is S_Count : constant Integer := Integer (Success_Count (R)); F_Count : constant Integer := Integer (Failure_Count (R)); E_Count : constant Integer := Integer (Error_Count (R)); begin New_Line; Put ("Total Tests Run: "); Put (Util.Strings.Image (Integer (Test_Count (R)))); New_Line; Put ("Successful Tests: "); Put (Util.Strings.Image (S_Count)); New_Line; Put ("Failed Assertions: "); Put (Util.Strings.Image (F_Count)); New_Line; Put ("Unexpected Errors: "); Put (Util.Strings.Image (E_Count)); New_Line; end Print_Summary; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; File : in out Ada.Text_IO.File_Type; R : in out Result'Class) is pragma Unreferenced (Engine); procedure Put (I : in Integer); procedure Put (S : in String); T : AUnit_Duration; procedure Put (I : in Integer) is begin Ada.Text_IO.Put (File, Integer'Image (I)); end Put; procedure Put (S : in String) is begin Put (File, S); end Put; procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure; begin Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>"); Put (File, "<TestRun"); if Elapsed (R) /= AUnit.Time_Measure.Null_Time then T := Get_Measure (Elapsed (R)); Put (File, " elapsed='"); Put_Measure (T); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Print_Summary (R); Put_Line (File, " <Statistics>"); Put (File, " <Tests>"); Put (File, Integer (Test_Count (R))); Put_Line (File, "</Tests>"); Put (File, " <FailuresTotal>"); Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R))); Put_Line (File, "</FailuresTotal>"); Put (File, " <Failures>"); Put (File, Integer (Failure_Count (R))); Put_Line (File, "</Failures>"); Put (File, " <Errors>"); Put (File, Integer (Error_Count (R))); Put_Line (File, "</Errors>"); Put_Line (File, " </Statistics>"); declare S : Result_Lists.List; begin Put_Line (File, " <SuccessfulTests>"); Successes (R, S); Dump_Result_List (File, S); Put_Line (File, " </SuccessfulTests>"); end; Put_Line (File, " <FailedTests>"); declare F : Result_Lists.List; begin Failures (R, F); Dump_Result_List (File, F); end; declare E : Result_Lists.List; begin Errors (R, E); Dump_Result_List (File, E); end; Put_Line (File, " </FailedTests>"); Put_Line (File, "</TestRun>"); end Report; ------------------ -- Report_Error -- ------------------ procedure Report_Test (File : in Ada.Text_IO.File_Type; Test : in Test_Result) is procedure Put (I : in Integer); procedure Put (S : in String); Is_Assert : Boolean; T : AUnit_Duration; procedure Put (I : in Integer) is begin Put (File, I); end Put; procedure Put (S : in String) is begin Put (File, S); end Put; procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure; begin Put (File, " <Test"); if Test.Elapsed /= AUnit.Time_Measure.Null_Time then T := Get_Measure (Test.Elapsed); Put (File, " elapsed='"); Put_Measure (T); Put_Line (File, "'>"); else Put_Line (File, ">"); end if; Put (File, " <Name>"); Put (File, Test.Test_Name.all); if Test.Routine_Name /= null then Put (File, " : "); Put (File, Test.Routine_Name.all); end if; Put_Line (File, "</Name>"); if Test.Failure /= null or else Test.Error /= null then if Test.Failure /= null then Is_Assert := True; else Is_Assert := False; end if; Put (File, " <FailureType>"); if Is_Assert then Put (File, "Assertion"); else Put (File, "Error"); end if; Put_Line (File, "</FailureType>"); Put (File, " <Message>"); if Is_Assert then Put (File, Test.Failure.Message.all); else Put (File, Test.Error.Exception_Name.all); end if; Put_Line (File, "</Message>"); if Is_Assert then Put_Line (File, " <Location>"); Put (File, " <File>"); Put (File, Test.Failure.Source_Name.all); Put_Line (File, "</File>"); Put (File, " <Line>"); Put (File, Test.Failure.Line); Put_Line (File, "</Line>"); Put_Line (File, " </Location>"); else Put_Line (File, " <Exception>"); Put (File, " <Message>"); Put (File, Test.Error.Exception_Name.all); Put_Line (File, "</Message>"); if Test.Error.Exception_Message /= null then Put (File, " <Information>"); Put (File, Test.Error.Exception_Message.all); Put_Line (File, "</Information>"); end if; if Test.Error.Traceback /= null then Put (File, " <Traceback>"); Put (File, Test.Error.Traceback.all); Put_Line (File, "</Traceback>"); end if; Put_Line (File, " </Exception>"); end if; end if; Put_Line (File, " </Test>"); end Report_Test; end Util.Tests.Reporter;
Print a summary of results on stdout
Print a summary of results on stdout
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
8b55ed554e8121c8b8b6994fc9f4ff2aacbdc974
src/util-beans-objects-maps.ads
src/util-beans-objects-maps.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
Declare the Create procedure Declare the Copy procedure as rename of Maps.Copy
Declare the Create procedure Declare the Copy procedure as rename of Maps.Copy
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a1e3cdfaa6d8aff5b29a6de1433ef4d1d2eeea8c
src/wiki-filters-collectors.ads
src/wiki-filters-collectors.ads
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Ordered_Maps; -- === Collector Filters === -- The <tt>Wiki.Filters.Collectors</tt> package defines two filters that can be used to -- collect words or links contained in a Wiki document. The collector filters are inserted -- in the filter chain and they collect the data as the Wiki text is parsed. After the -- parsing, the collector filters have collected either the words or the links and they -- can be queried by using the <tt>Find</tt> or <tt>Iterate</tt> operations. package Wiki.Filters.Collectors is pragma Preelaborate; package WString_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Natural, "<" => "<", "=" => "="); subtype Map is WString_Maps.Map; subtype Cursor is WString_Maps.Cursor; -- ------------------------------ -- General purpose collector type -- ------------------------------ type Collector_Type is new Filter_Type with private; type Collector_Type_Access is access all Collector_Type'Class; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)); -- ------------------------------ -- Word Collector type -- ------------------------------ type Word_Collector_Type is new Collector_Type with private; type Word_Collector_Type_Access is access all Word_Collector_Type'Class; -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a link. procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- ------------------------------ -- Link Collector type -- ------------------------------ type Link_Collector_Type is new Collector_Type with private; type Link_Collector_Type_Access is access all Link_Collector_Type'Class; -- Add a link. overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Push a HTML node with the given tag to the document. overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); private type Collector_Type is new Filter_Type with record Items : WString_Maps.Map; end record; type Word_Collector_Type is new Collector_Type with null record; procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString); type Link_Collector_Type is new Collector_Type with null record; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String); end Wiki.Filters.Collectors;
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Ordered_Maps; -- === Collector Filters === -- The <tt>Wiki.Filters.Collectors</tt> package defines two filters that can be used to -- collect words or links contained in a Wiki document. The collector filters are inserted -- in the filter chain and they collect the data as the Wiki text is parsed. After the -- parsing, the collector filters have collected either the words or the links and they -- can be queried by using the <tt>Find</tt> or <tt>Iterate</tt> operations. package Wiki.Filters.Collectors is pragma Preelaborate; package WString_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Natural, "<" => "<", "=" => "="); subtype Map is WString_Maps.Map; subtype Cursor is WString_Maps.Cursor; -- ------------------------------ -- General purpose collector type -- ------------------------------ type Collector_Type is new Filter_Type with private; type Collector_Type_Access is access all Collector_Type'Class; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)); -- ------------------------------ -- Word Collector type -- ------------------------------ type Word_Collector_Type is new Collector_Type with private; type Word_Collector_Type_Access is access all Word_Collector_Type'Class; -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a link. procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- ------------------------------ -- Link Collector type -- ------------------------------ type Link_Collector_Type is new Collector_Type with private; type Link_Collector_Type_Access is access all Link_Collector_Type'Class; -- Add a link. overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Push a HTML node with the given tag to the document. overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); -- ------------------------------ -- Image Collector type -- ------------------------------ type Image_Collector_Type is new Collector_Type with private; type Image_Collector_Type_Access is access all Image_Collector_Type'Class; -- Add an image. overriding procedure Add_Image (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); private type Collector_Type is new Filter_Type with record Items : WString_Maps.Map; end record; type Word_Collector_Type is new Collector_Type with null record; procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString); type Link_Collector_Type is new Collector_Type with null record; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String); type Image_Collector_Type is new Collector_Type with null record; end Wiki.Filters.Collectors;
Declare the Image_Collector_Type to collect images used in a wiki page
Declare the Image_Collector_Type to collect images used in a wiki page
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2564d37316162825f3111134a6e8f795818fb2ab
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
awt/src/wayland/orka-contexts-egl-wayland-awt.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Logging; with Orka.Terminals; with EGL.Objects.Configs; with EGL.Objects.Surfaces; with Wayland.Protocols.Client.AWT; package body Orka.Contexts.EGL.Wayland.AWT is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; procedure Log is new Orka.Logging.Generic_Log (Window_System); procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State; use Standard.AWT.Monitors; begin Log (Debug, "Window visible on monitor " & (+State.Name)); Log (Debug, " offset: " & Trim (State.X'Image) & ", " & Trim (State.Y'Image)); Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh)); end Print_Monitor; ---------------------------------------------------------------------------- overriding function Width (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Width; end Width; overriding function Height (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Height; end Height; ---------------------------------------------------------------------------- function Framebuffer_Resized (Object : in out AWT_Window) return Boolean is Result : constant Boolean := Object.Resize; begin Object.Resize := False; return Result; end Framebuffer_Resized; overriding procedure On_Configure (Object : in out AWT_Window; State : Standard.AWT.Windows.Window_State) is begin Log (Debug, "Configured window surface"); Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Log (Debug, " margin: " & Trim (State.Margin'Image)); Object.Resize := State.Visible and State.Width > 0 and State.Height > 0; end On_Configure; overriding procedure On_Move (Object : in out AWT_Window; Monitor : Standard.AWT.Monitors.Monitor'Class; Presence : Standard.AWT.Windows.Monitor_Presence) is use all type Standard.AWT.Windows.Monitor_Presence; use Standard.AWT.Monitors; begin case Presence is when Entered => Print_Monitor (Monitor); when Left => Log (Debug, "Window not visible on monitor " & (+Monitor.State.Name)); end case; end On_Move; ---------------------------------------------------------------------------- overriding procedure Make_Current (Object : AWT_Context; Window : in out Orka.Windows.Window'Class) is begin if Window not in AWT_Window'Class then raise Constraint_Error; end if; AWT_Window (Window).Make_Current (Object.Context); end Make_Current; overriding function Create_Context (Version : Orka.Contexts.Context_Version; Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is begin if not Standard.AWT.Is_Initialized then Standard.AWT.Initialize; end if; return Create_Context (Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all), Version, Flags); end Create_Context; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return AWT_Window is package EGL_Configs renames Standard.EGL.Objects.Configs; use all type Standard.EGL.Objects.Contexts.Buffer_Kind; package SU renames Standard.AWT.SU; function Flags return String is Result : SU.Unbounded_String; begin if Visible then SU.Append (Result, " visible"); end if; if Resizable then SU.Append (Result, " resizable"); end if; if Transparent then SU.Append (Result, " transparent"); end if; return Trim (SU.To_String (Result)); end Flags; Object : AWT_Context renames AWT_Context (Context); begin return Result : AWT_Window do declare Configs : constant EGL_Configs.Config_Array := EGL_Configs.Get_Configs (Object.Context.Display, 8, 8, 8, (if Transparent then 8 else 0), 24, 8, EGL_Configs.Sample_Size (Samples)); Used_Config : EGL_Configs.Config renames Configs (Configs'First); begin Log (Debug, "Available EGL configs: " & Trim (Natural'Image (Configs'Length))); Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => False); Result.Create_Window ("", Title, Width, Height, Visible => Visible, Resizable => Resizable, Decorated => True, Transparent => Transparent); Result.Make_Current (Object.Context); pragma Assert (Object.Context.Buffer = Back); Log (Debug, "Created AWT window"); Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Log (Debug, " flags: " & Flags); Log (Debug, " framebuffer:"); declare State : constant EGL_Configs.Config_State := Used_Config.State; begin Log (Debug, " colors: " & Trim (State.Red'Image) & " " & Trim (State.Green'Image) & " " & Trim (State.Blue'Image) & " " & Trim (State.Alpha'Image)); Log (Debug, " depth: " & Trim (State.Depth'Image)); Log (Debug, " stencil: " & Trim (State.Stencil'Image)); Log (Debug, " samples: " & Trim (State.Samples'Image)); end; end; end return; end Create_Window; end Orka.Contexts.EGL.Wayland.AWT;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Logging; with Orka.Terminals; with EGL.Objects.Configs; with Wayland.Protocols.Client.AWT; package body Orka.Contexts.EGL.Wayland.AWT is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; procedure Log is new Orka.Logging.Generic_Log (Window_System); procedure Print_Monitor (Monitor : Standard.AWT.Monitors.Monitor'Class) is State : constant Standard.AWT.Monitors.Monitor_State := Monitor.State; use Standard.AWT.Monitors; begin Log (Debug, "Window visible on monitor " & (+State.Name)); Log (Debug, " offset: " & Trim (State.X'Image) & ", " & Trim (State.Y'Image)); Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Log (Debug, " refresh: " & Orka.Terminals.Image (State.Refresh)); end Print_Monitor; ---------------------------------------------------------------------------- overriding function Width (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Width; end Width; overriding function Height (Object : AWT_Window) return Positive is State : Standard.AWT.Windows.Framebuffer_State renames Object.State; begin return State.Height; end Height; ---------------------------------------------------------------------------- function Framebuffer_Resized (Object : in out AWT_Window) return Boolean is Result : constant Boolean := Object.Resize; begin Object.Resize := False; return Result; end Framebuffer_Resized; overriding procedure On_Configure (Object : in out AWT_Window; State : Standard.AWT.Windows.Window_State) is begin Log (Debug, "Configured window surface"); Log (Debug, " size: " & Trim (State.Width'Image) & " × " & Trim (State.Height'Image)); Log (Debug, " margin: " & Trim (State.Margin'Image)); Object.Resize := State.Visible and State.Width > 0 and State.Height > 0; end On_Configure; overriding procedure On_Move (Object : in out AWT_Window; Monitor : Standard.AWT.Monitors.Monitor'Class; Presence : Standard.AWT.Windows.Monitor_Presence) is use all type Standard.AWT.Windows.Monitor_Presence; use Standard.AWT.Monitors; begin case Presence is when Entered => Print_Monitor (Monitor); when Left => Log (Debug, "Window not visible on monitor " & (+Monitor.State.Name)); end case; end On_Move; ---------------------------------------------------------------------------- overriding procedure Make_Current (Object : AWT_Context; Window : in out Orka.Windows.Window'Class) is begin if Window not in AWT_Window'Class then raise Constraint_Error; end if; AWT_Window (Window).Make_Current (Object.Context); end Make_Current; overriding function Create_Context (Version : Orka.Contexts.Context_Version; Flags : Orka.Contexts.Context_Flags := (others => False)) return AWT_Context is begin if not Standard.AWT.Is_Initialized then Standard.AWT.Initialize; end if; return Create_Context (Standard.Wayland.Protocols.Client.AWT.Get_Display (Standard.AWT.Wayland.Get_Display.all), Version, Flags); end Create_Context; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return AWT_Window is package EGL_Configs renames Standard.EGL.Objects.Configs; use all type Standard.EGL.Objects.Contexts.Buffer_Kind; package SU renames Standard.AWT.SU; function Flags return String is Result : SU.Unbounded_String; begin if Visible then SU.Append (Result, " visible"); end if; if Resizable then SU.Append (Result, " resizable"); end if; if Transparent then SU.Append (Result, " transparent"); end if; return Trim (SU.To_String (Result)); end Flags; Object : AWT_Context renames AWT_Context (Context); begin return Result : AWT_Window do declare Configs : constant EGL_Configs.Config_Array := EGL_Configs.Get_Configs (Object.Context.Display, 8, 8, 8, (if Transparent then 8 else 0), 24, 8, EGL_Configs.Sample_Size (Samples)); Used_Config : EGL_Configs.Config renames Configs (Configs'First); begin Log (Debug, "Available EGL configs: " & Trim (Natural'Image (Configs'Length))); Result.Set_EGL_Data (Object.Context, Used_Config, sRGB => False); Result.Create_Window ("", Title, Width, Height, Visible => Visible, Resizable => Resizable, Decorated => True, Transparent => Transparent); Result.Make_Current (Object.Context); pragma Assert (Object.Context.Buffer = Back); Log (Debug, "Created AWT window"); Log (Debug, " size: " & Trim (Width'Image) & " × " & Trim (Height'Image)); Log (Debug, " flags: " & Flags); Log (Debug, " framebuffer:"); declare State : constant EGL_Configs.Config_State := Used_Config.State; begin Log (Debug, " colors: " & Trim (State.Red'Image) & " " & Trim (State.Green'Image) & " " & Trim (State.Blue'Image) & " " & Trim (State.Alpha'Image)); Log (Debug, " depth: " & Trim (State.Depth'Image)); Log (Debug, " stencil: " & Trim (State.Stencil'Image)); Log (Debug, " samples: " & Trim (State.Samples'Image)); end; end; end return; end Create_Window; end Orka.Contexts.EGL.Wayland.AWT;
Remove with'ing unused package
awt: Remove with'ing unused package Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f2c66ba99bd0dc5aaf84b5764b59b24e6f5486f4
src/gen-commands-generate.ads
src/gen-commands-generate.ads
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Generate is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Generate;
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Generate is -- ------------------------------ -- Generator Command -- ------------------------------ type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler); end Gen.Commands.Generate;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4b98ee8b85825200625938afd0a94a0be26814f8
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ procedure Do_Request_Token (App : in Application; URI : in String; Data : in String; Cred : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1)); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); Cred.Access_Token := P.Get ("access_token"); Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", "")); Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", "")); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return; end if; end; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end Do_Request_Token; -- ------------------------------ -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=password" & "&" & Security.OAuth.USERNAME & "=" & Username & "&" & Security.OAuth.PASSWORD & "=" & Password & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0} - resource owner password", URI); Do_Request_Token (App, URI, Data, Token); end Request_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth-clients -- OAuth Client Security -- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; with Security.Random; package body Security.OAuth.Clients is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ Random_Generator : Security.Random.Generator; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is begin -- Generate the random sequence. return Random_Generator.Generate (Bits); end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Grant_Type) return String is begin return To_String (From.Access_Token); end Get_Name; -- ------------------------------ -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) -- ------------------------------ function Get_Authorization (From : in Grant_Type) return String is begin return "Bearer " & To_String (From.Access_Token); end Get_Authorization; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.STATE & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.GRANT_TYPE & "=authorization_code" & "&" & Security.OAuth.CODE & "=" & Code & "&" & Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); begin Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ procedure Do_Request_Token (App : in Application; URI : in String; Data : in String; Cred : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1)); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); Cred.Access_Token := P.Get ("access_token"); Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", "")); Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", "")); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return; end if; end; exception -- Handle a Program_Error exception that could be raised by AWS when SSL -- is not supported. Emit a log error so that we can trouble this kins of -- problem more easily. when E : Program_Error => Log.Error ("Cannot get access token from {0}: program error: {1}", URI, Ada.Exceptions.Exception_Message (E)); raise; end Do_Request_Token; -- ------------------------------ -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class) is Client : Util.Http.Clients.Client; Data : constant String := Security.OAuth.GRANT_TYPE & "=password" & "&" & Security.OAuth.USERNAME & "=" & Username & "&" & Security.OAuth.PASSWORD & "=" & Password & "&" & Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.SCOPE & "=" & Scope & "&" & Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0} - resource owner password", URI); Do_Request_Token (App, URI, Data, Token); end Request_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
Implement the Get_Authorization function
Implement the Get_Authorization function
Ada
apache-2.0
stcarrez/ada-security
641a322e2850904abac0a865efb9d2783f93ce2f
src/security-auth.ads
src/security-auth.ads
----------------------------------------------------------------------- -- 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; type Factory_Access is not null access function (Provider : in String) return Manager_Access; -- Set the default factory to use. procedure Set_Default_Factory (Factory : in Factory_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; overriding procedure Finalize (Realm : in out Manager); 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"; -- Use the Yahoo! OpenID Connect Basic Client PROVIDER_YAHOO : constant String := "yahoo"; 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; type Factory_Access is not null access function (Provider : in String) return Manager_Access; -- Set the default factory to use. procedure Set_Default_Factory (Factory : in Factory_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; Nonce : Unbounded_String; 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; overriding procedure Finalize (Realm : in out Manager); 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;
Add Nonce to the Association record and declare the PROVIDER_YAHOO
Add Nonce to the Association record and declare the PROVIDER_YAHOO
Ada
apache-2.0
stcarrez/ada-security
f1549e07ad371d50186db25711292fc3fb7d1803
src/gen-commands-model.ads
src/gen-commands-model.ads
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Model is -- ------------------------------ -- Model Creation Command -- ------------------------------ -- This command adds a model file to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Model;
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Model is -- ------------------------------ -- Model Creation Command -- ------------------------------ -- This command adds a model file to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler); end Gen.Commands.Model;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
dc4b62215a6cdcfbb2644d6199fb3590bef0d002
hal/src/hal-bitmap.ads
hal/src/hal-bitmap.ads
with System; package HAL.Bitmap is type Orientation_Mode is (Default, Portrait, Landscape); subtype Actual_Orientation is Orientation_Mode range Portrait .. Landscape; type Bitmap_Color_Mode is (ARGB_8888, RGB_888, RGB_565, ARGB_1555, ARGB_4444, L_8, AL_44, AL_88, L_4, A_8, A_4) with Size => 4; function Bits_Per_Pixel (Mode : Bitmap_Color_Mode) return Positive is (case Mode is when ARGB_8888 => 32, when RGB_888 => 24, when RGB_565 | ARGB_1555 | ARGB_4444 | AL_88 => 16, when L_8 | AL_44 | A_8 => 8, when L_4 | A_4 => 4); type Bitmap_Buffer is tagged record Addr : System.Address; Width : Natural; Height : Natural; -- Width and Height of the buffer. Note that it's the user-visible width -- (see below for the meaning of the Swapped value). Color_Mode : Bitmap_Color_Mode; -- The buffer color mode. Note that not all color modes are supported by -- the hardware acceleration (if any), so you need to check your actual -- hardware to optimize buffer transfers. Swapped : Boolean := False; -- If Swap is set, then operations on this buffer will consider: -- Width0 = Height -- Height0 = Width -- Y0 = Buffer.Width - X - 1 -- X0 = Y -- -- As an example, the Bitmap buffer that corresponds to a 240x320 -- swapped display (to display images in landscape mode) with have -- the following values: -- Width => 320 -- Height => 240 -- Swapped => True -- So Put_Pixel (Buffer, 30, 10, Color) will place the pixel at -- Y0 = 320 - 30 - 1 = 289 -- X0 = 10 end record; type Bitmap_Color is record Alpha : Byte; Red : Byte; Green : Byte; Blue : Byte; end record with Size => 32; for Bitmap_Color use record Blue at 0 range 0 .. 7; Green at 1 range 0 .. 7; Red at 2 range 0 .. 7; Alpha at 3 range 0 .. 7; end record; Black : constant Bitmap_Color := (255, 0, 0, 0); Blue : constant Bitmap_Color := (255, 0, 0, 255); Light_Blue : constant Bitmap_Color := (255, 173, 216, 230); Brown : constant Bitmap_Color := (255, 165, 42, 42); Cyan : constant Bitmap_Color := (255, 0, 255, 255); Gray : constant Bitmap_Color := (255, 190, 190, 190); Light_Gray : constant Bitmap_Color := (255, 211, 211, 211); Green : constant Bitmap_Color := (255, 0, 255, 0); Light_Green : constant Bitmap_Color := (255, 144, 238, 144); Magenta : constant Bitmap_Color := (255, 255, 0, 255); Red : constant Bitmap_Color := (255, 255, 0, 0); Orange : constant Bitmap_Color := (255, 255, 69, 0); Violet : constant Bitmap_Color := (255, 238, 130, 238); Yellow : constant Bitmap_Color := (255, 255, 255, 0); White : constant Bitmap_Color := (255, 255, 255, 255); Transparent : constant Bitmap_Color := (0, 0, 0, 0); procedure Set_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Bitmap_Color); procedure Set_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Word); procedure Set_Pixel_Blend (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Bitmap_Color); function Get_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural) return Bitmap_Color; function Get_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural) return Word; procedure Fill (Buffer : Bitmap_Buffer; Color : Bitmap_Color); -- Fill the specified buffer with 'Color' procedure Fill (Buffer : Bitmap_Buffer; Color : Word); -- Same as above, using the destination buffer native color representation procedure Fill_Rect (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Fill the specified area of the buffer with 'Color' procedure Fill_Rect (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Same as above, using the destination buffer native color representation procedure Copy_Rect (Src_Buffer : Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Bg_Buffer : Bitmap_Buffer'Class; X_Bg : Natural; Y_Bg : Natural; Width : Natural; Height : Natural); procedure Copy_Rect (Src_Buffer : Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Width : Natural; Height : Natural); procedure Copy_Rect_Blend (Src_Buffer : Bitmap_Buffer; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer'Class; X_Dst : Natural; Y_Dst : Natural; Width : Natural; Height : Natural); procedure Draw_Vertical_Line (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Height : Integer); procedure Draw_Vertical_Line (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Height : Integer); procedure Draw_Horizontal_Line (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer); procedure Draw_Horizontal_Line (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer); procedure Draw_Rect (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Draws a rectangle function Buffer_Size (Buffer : Bitmap_Buffer) return Natural; function Bitmap_Color_To_Word (Mode : Bitmap_Color_Mode; Col : Bitmap_Color) return Word; -- Translates the DMA2D Color into native buffer color function Word_To_Bitmap_Color (Mode : Bitmap_Color_Mode; Col : Word) return Bitmap_Color; -- Translates the native buffer color into DMA2D Color procedure Wait_Transfer (Buffer : Bitmap_Buffer); -- Makes sure the DMA2D transfers are done end HAL.Bitmap;
with System; package HAL.Bitmap is type Orientation_Mode is (Default, Portrait, Landscape); subtype Actual_Orientation is Orientation_Mode range Portrait .. Landscape; type Bitmap_Color_Mode is (ARGB_8888, RGB_888, RGB_565, ARGB_1555, ARGB_4444, L_8, AL_44, AL_88, L_4, A_8, A_4) with Size => 4; function Bits_Per_Pixel (Mode : Bitmap_Color_Mode) return Positive is (case Mode is when ARGB_8888 => 32, when RGB_888 => 24, when RGB_565 | ARGB_1555 | ARGB_4444 | AL_88 => 16, when L_8 | AL_44 | A_8 => 8, when L_4 | A_4 => 4); type Bitmap_Buffer is tagged record Addr : System.Address; Width : Natural; Height : Natural; -- Width and Height of the buffer. Note that it's the user-visible width -- (see below for the meaning of the Swapped value). Color_Mode : Bitmap_Color_Mode; -- The buffer color mode. Note that not all color modes are supported by -- the hardware acceleration (if any), so you need to check your actual -- hardware to optimize buffer transfers. Swapped : Boolean := False; -- If Swap is set, then operations on this buffer will consider: -- Width0 = Height -- Height0 = Width -- Y0 = Buffer.Width - X - 1 -- X0 = Y -- -- As an example, the Bitmap buffer that corresponds to a 240x320 -- swapped display (to display images in landscape mode) with have -- the following values: -- Width => 320 -- Height => 240 -- Swapped => True -- So Put_Pixel (Buffer, 30, 10, Color) will place the pixel at -- Y0 = 320 - 30 - 1 = 289 -- X0 = 10 end record; type Bitmap_Color is record Alpha : Byte; Red : Byte; Green : Byte; Blue : Byte; end record with Size => 32; for Bitmap_Color use record Blue at 0 range 0 .. 7; Green at 1 range 0 .. 7; Red at 2 range 0 .. 7; Alpha at 3 range 0 .. 7; end record; procedure Set_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Bitmap_Color); procedure Set_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Word); procedure Set_Pixel_Blend (Buffer : Bitmap_Buffer; X : Natural; Y : Natural; Value : Bitmap_Color); function Get_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural) return Bitmap_Color; function Get_Pixel (Buffer : Bitmap_Buffer; X : Natural; Y : Natural) return Word; procedure Fill (Buffer : Bitmap_Buffer; Color : Bitmap_Color); -- Fill the specified buffer with 'Color' procedure Fill (Buffer : Bitmap_Buffer; Color : Word); -- Same as above, using the destination buffer native color representation procedure Fill_Rect (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Fill the specified area of the buffer with 'Color' procedure Fill_Rect (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Same as above, using the destination buffer native color representation procedure Copy_Rect (Src_Buffer : Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Bg_Buffer : Bitmap_Buffer'Class; X_Bg : Natural; Y_Bg : Natural; Width : Natural; Height : Natural); procedure Copy_Rect (Src_Buffer : Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Width : Natural; Height : Natural); procedure Copy_Rect_Blend (Src_Buffer : Bitmap_Buffer; X_Src : Natural; Y_Src : Natural; Dst_Buffer : Bitmap_Buffer'Class; X_Dst : Natural; Y_Dst : Natural; Width : Natural; Height : Natural); procedure Draw_Vertical_Line (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Height : Integer); procedure Draw_Vertical_Line (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Height : Integer); procedure Draw_Horizontal_Line (Buffer : Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer); procedure Draw_Horizontal_Line (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer); procedure Draw_Rect (Buffer : Bitmap_Buffer; Color : Bitmap_Color; X : Integer; Y : Integer; Width : Integer; Height : Integer); -- Draws a rectangle function Buffer_Size (Buffer : Bitmap_Buffer) return Natural; function Bitmap_Color_To_Word (Mode : Bitmap_Color_Mode; Col : Bitmap_Color) return Word; -- Translates the DMA2D Color into native buffer color function Word_To_Bitmap_Color (Mode : Bitmap_Color_Mode; Col : Word) return Bitmap_Color; -- Translates the native buffer color into DMA2D Color procedure Wait_Transfer (Buffer : Bitmap_Buffer); -- Makes sure the DMA2D transfers are done Transparent : constant Bitmap_Color := (000, 000, 000, 000); Dark_Red : constant Bitmap_Color := (255, 139, 000, 000); Brown : constant Bitmap_Color := (255, 165, 042, 042); Firebrick : constant Bitmap_Color := (255, 178, 034, 034); Crimson : constant Bitmap_Color := (255, 220, 020, 060); Red : constant Bitmap_Color := (255, 255, 000, 000); Tomato : constant Bitmap_Color := (255, 255, 099, 071); Coral : constant Bitmap_Color := (255, 255, 127, 080); Indian_Red : constant Bitmap_Color := (255, 205, 092, 092); Light_Coral : constant Bitmap_Color := (255, 240, 128, 128); Dark_Salmon : constant Bitmap_Color := (255, 233, 150, 122); Salmon : constant Bitmap_Color := (255, 250, 128, 114); Light_Salmon : constant Bitmap_Color := (255, 255, 160, 122); Dark_Orange : constant Bitmap_Color := (255, 255, 140, 000); Orange : constant Bitmap_Color := (255, 255, 165, 000); Light_Orange : constant Bitmap_Color := (255, 255, 069, 000); Gold : constant Bitmap_Color := (255, 255, 215, 000); Dark_Golden_Rod : constant Bitmap_Color := (255, 184, 134, 011); Golden_Rod : constant Bitmap_Color := (255, 218, 165, 032); Pale_Golden_Rod : constant Bitmap_Color := (255, 238, 232, 170); Dark_Khaki : constant Bitmap_Color := (255, 189, 183, 107); Khaki : constant Bitmap_Color := (255, 240, 230, 140); Olive : constant Bitmap_Color := (255, 128, 128, 000); Yellow : constant Bitmap_Color := (255, 255, 255, 000); Yellow_Green : constant Bitmap_Color := (255, 154, 205, 050); Dark_Olive_Green : constant Bitmap_Color := (255, 085, 107, 047); Olive_Drab : constant Bitmap_Color := (255, 107, 142, 035); Lawn_Green : constant Bitmap_Color := (255, 124, 252, 000); Chart_Reuse : constant Bitmap_Color := (255, 127, 255, 000); Green_Yellow : constant Bitmap_Color := (255, 173, 255, 047); Dark_Green : constant Bitmap_Color := (255, 000, 100, 000); Green : constant Bitmap_Color := (255, 000, 255, 000); Maroon : constant Bitmap_Color := (255, 128, 000, 000); Forest_Green : constant Bitmap_Color := (255, 034, 139, 034); Lime : constant Bitmap_Color := (255, 000, 255, 000); Lime_Green : constant Bitmap_Color := (255, 050, 205, 050); Light_Green : constant Bitmap_Color := (255, 144, 238, 144); Pale_Green : constant Bitmap_Color := (255, 152, 251, 152); Dark_Sea_Green : constant Bitmap_Color := (255, 143, 188, 143); Medium_Spring_Green : constant Bitmap_Color := (255, 000, 250, 154); Spring_Green : constant Bitmap_Color := (255, 000, 255, 127); Sea_Green : constant Bitmap_Color := (255, 046, 139, 087); Medium_Aqua_Marine : constant Bitmap_Color := (255, 102, 205, 170); Medium_Sea_Green : constant Bitmap_Color := (255, 060, 179, 113); Light_Sea_Green : constant Bitmap_Color := (255, 032, 178, 170); Dark_Slate_Gray : constant Bitmap_Color := (255, 047, 079, 079); Teal : constant Bitmap_Color := (255, 000, 128, 128); Dark_Cyan : constant Bitmap_Color := (255, 000, 139, 139); Aqua : constant Bitmap_Color := (255, 000, 255, 255); Cyan : constant Bitmap_Color := (255, 000, 255, 255); Light_Cyan : constant Bitmap_Color := (255, 224, 255, 255); Dark_Turquoise : constant Bitmap_Color := (255, 000, 206, 209); Turquoise : constant Bitmap_Color := (255, 064, 224, 208); Medium_Turquoise : constant Bitmap_Color := (255, 072, 209, 204); Pale_Turquoise : constant Bitmap_Color := (255, 175, 238, 238); Aqua_Marine : constant Bitmap_Color := (255, 127, 255, 212); Powder_Blue : constant Bitmap_Color := (255, 176, 224, 230); Cadet_Blue : constant Bitmap_Color := (255, 095, 158, 160); Steel_Blue : constant Bitmap_Color := (255, 070, 130, 180); Corn_Flower_Blue : constant Bitmap_Color := (255, 100, 149, 237); Deep_Sky_Blue : constant Bitmap_Color := (255, 000, 191, 255); Dodger_Blue : constant Bitmap_Color := (255, 030, 144, 255); Light_Blue : constant Bitmap_Color := (255, 173, 216, 230); Sky_Blue : constant Bitmap_Color := (255, 135, 206, 235); Light_Sky_Blue : constant Bitmap_Color := (255, 135, 206, 250); Midnight_Blue : constant Bitmap_Color := (255, 025, 025, 112); Navy : constant Bitmap_Color := (255, 000, 000, 128); Dark_Blue : constant Bitmap_Color := (255, 000, 000, 139); Medium_Blue : constant Bitmap_Color := (255, 000, 000, 205); Blue : constant Bitmap_Color := (255, 000, 000, 255); Royal_Blue : constant Bitmap_Color := (255, 065, 105, 225); Blue_Violet : constant Bitmap_Color := (255, 138, 043, 226); Indigo : constant Bitmap_Color := (255, 075, 000, 130); Dark_Slate_Blue : constant Bitmap_Color := (255, 072, 061, 139); Slate_Blue : constant Bitmap_Color := (255, 106, 090, 205); Medium_Slate_Blue : constant Bitmap_Color := (255, 123, 104, 238); Medium_Purple : constant Bitmap_Color := (255, 147, 112, 219); Dark_Magenta : constant Bitmap_Color := (255, 139, 000, 139); Dark_Violet : constant Bitmap_Color := (255, 148, 000, 211); Dark_Orchid : constant Bitmap_Color := (255, 153, 050, 204); Medium_Orchid : constant Bitmap_Color := (255, 186, 085, 211); Purple : constant Bitmap_Color := (255, 128, 000, 128); Thistle : constant Bitmap_Color := (255, 216, 191, 216); Plum : constant Bitmap_Color := (255, 221, 160, 221); Violet : constant Bitmap_Color := (255, 238, 130, 238); Magenta : constant Bitmap_Color := (255, 255, 000, 255); Orchid : constant Bitmap_Color := (255, 218, 112, 214); Medium_Violet_Red : constant Bitmap_Color := (255, 199, 021, 133); Pale_Violet_Red : constant Bitmap_Color := (255, 219, 112, 147); Deep_Pink : constant Bitmap_Color := (255, 255, 020, 147); Hot_Pink : constant Bitmap_Color := (255, 255, 105, 180); Light_Pink : constant Bitmap_Color := (255, 255, 182, 193); Pink : constant Bitmap_Color := (255, 255, 192, 203); Antique_White : constant Bitmap_Color := (255, 250, 235, 215); Beige : constant Bitmap_Color := (255, 245, 245, 220); Bisque : constant Bitmap_Color := (255, 255, 228, 196); Blanched_Almond : constant Bitmap_Color := (255, 255, 235, 205); Wheat : constant Bitmap_Color := (255, 245, 222, 179); Corn_Silk : constant Bitmap_Color := (255, 255, 248, 220); Lemon_Chiffon : constant Bitmap_Color := (255, 255, 250, 205); Light_Yellow : constant Bitmap_Color := (255, 255, 255, 224); Saddle_Brown : constant Bitmap_Color := (255, 139, 069, 019); Sienna : constant Bitmap_Color := (255, 160, 082, 045); Chocolate : constant Bitmap_Color := (255, 210, 105, 030); Peru : constant Bitmap_Color := (255, 205, 133, 063); Sandy_Brown : constant Bitmap_Color := (255, 244, 164, 096); Burly_Wood : constant Bitmap_Color := (255, 222, 184, 135); Tan : constant Bitmap_Color := (255, 210, 180, 140); Rosy_Brown : constant Bitmap_Color := (255, 188, 143, 143); Moccasin : constant Bitmap_Color := (255, 255, 228, 181); Navajo_White : constant Bitmap_Color := (255, 255, 222, 173); Peach_Puff : constant Bitmap_Color := (255, 255, 218, 185); Misty_Rose : constant Bitmap_Color := (255, 255, 228, 225); Lavender_Blush : constant Bitmap_Color := (255, 255, 240, 245); Linen : constant Bitmap_Color := (255, 250, 240, 230); Old_Lace : constant Bitmap_Color := (255, 253, 245, 230); Papaya_Whip : constant Bitmap_Color := (255, 255, 239, 213); Sea_Shell : constant Bitmap_Color := (255, 255, 245, 238); Mint_Cream : constant Bitmap_Color := (255, 245, 255, 250); Slate_Gray : constant Bitmap_Color := (255, 112, 128, 144); Light_Slate_Gray : constant Bitmap_Color := (255, 119, 136, 153); Light_Steel_Blue : constant Bitmap_Color := (255, 176, 196, 222); Lavender : constant Bitmap_Color := (255, 230, 230, 250); Floral_White : constant Bitmap_Color := (255, 255, 250, 240); Alice_Blue : constant Bitmap_Color := (255, 240, 248, 255); Ghost_White : constant Bitmap_Color := (255, 248, 248, 255); Honeydew : constant Bitmap_Color := (255, 240, 255, 240); Ivory : constant Bitmap_Color := (255, 255, 255, 240); Azure : constant Bitmap_Color := (255, 240, 255, 255); Snow : constant Bitmap_Color := (255, 255, 250, 250); Black : constant Bitmap_Color := (255, 000, 000, 000); Dim_Grey : constant Bitmap_Color := (255, 105, 105, 105); Grey : constant Bitmap_Color := (255, 128, 128, 128); Gray : constant Bitmap_Color := (255, 190, 190, 190); Dark_Grey : constant Bitmap_Color := (255, 169, 169, 169); Silver : constant Bitmap_Color := (255, 192, 192, 192); Light_Grey : constant Bitmap_Color := (255, 211, 211, 211); Gainsboro : constant Bitmap_Color := (255, 220, 220, 220); White_Smoke : constant Bitmap_Color := (255, 245, 245, 245); White : constant Bitmap_Color := (255, 255, 255, 255); end HAL.Bitmap;
Add more color definitions
HAL.Bitmap: Add more color definitions
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
c1abcb8572211376f49699bcc3c55b0b76d655f0
src/natools.ads
src/natools.ads
------------------------------------------------------------------------------ -- Copyright (c) 2011, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools is a collection of miscellaneous small utilities gathered in one -- -- shared library. -- ------------------------------------------------------------------------------ package Natools is pragma Pure (Natools); end Natools;
------------------------------------------------------------------------------ -- Copyright (c) 2011, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools is a collection of miscellaneous small utilities gathered in one -- -- shared library. -- ------------------------------------------------------------------------------ package Natools is pragma Pure (Natools); type Meaningless_Type is (Meaningless_Value); end Natools;
add Meaningless_Type to help instantiation of interpreters without meaningful context or state
natools: add Meaningless_Type to help instantiation of interpreters without meaningful context or state
Ada
isc
faelys/natools
29f6eb362c88bca574ca8911dba3ccdcdb173527
src/dw1000-types.ads
src/dw1000-types.ads
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with Interfaces; package DW1000.Types with SPARK_Mode => On is type Bits_1 is mod 2**1 with Size => 1; type Bits_2 is mod 2**2 with Size => 2; type Bits_3 is mod 2**3 with Size => 3; type Bits_4 is mod 2**4 with Size => 4; type Bits_5 is mod 2**5 with Size => 5; type Bits_6 is mod 2**6 with Size => 6; type Bits_7 is mod 2**7 with Size => 7; subtype Bits_8 is Interfaces.Unsigned_8; type Bits_9 is mod 2**9 with Size => 9; type Bits_10 is mod 2**10 with Size => 10; type Bits_11 is mod 2**11 with Size => 11; type Bits_12 is mod 2**12 with Size => 12; type Bits_13 is mod 2**13 with Size => 13; type Bits_14 is mod 2**14 with Size => 14; type Bits_15 is mod 2**15 with Size => 15; subtype Bits_16 is Interfaces.Unsigned_16; type Bits_17 is mod 2**17 with Size => 17; type Bits_18 is mod 2**18 with Size => 18; type Bits_19 is mod 2**19 with Size => 19; type Bits_20 is mod 2**20 with Size => 20; type Bits_21 is mod 2**21 with Size => 21; type Bits_22 is mod 2**22 with Size => 22; type Bits_23 is mod 2**23 with Size => 23; type Bits_24 is mod 2**24 with Size => 24; type Bits_25 is mod 2**25 with Size => 25; type Bits_26 is mod 2**26 with Size => 26; type Bits_27 is mod 2**27 with Size => 27; type Bits_28 is mod 2**28 with Size => 28; type Bits_29 is mod 2**29 with Size => 29; type Bits_30 is mod 2**30 with Size => 30; type Bits_31 is mod 2**31 with Size => 31; subtype Bits_32 is Interfaces.Unsigned_32; type Bits_33 is mod 2**33 with Size => 33; type Bits_34 is mod 2**34 with Size => 34; type Bits_35 is mod 2**35 with Size => 35; type Bits_36 is mod 2**36 with Size => 36; type Bits_37 is mod 2**37 with Size => 37; type Bits_38 is mod 2**38 with Size => 38; type Bits_39 is mod 2**39 with Size => 39; type Bits_40 is mod 2**40 with Size => 40; type Bits_41 is mod 2**41 with Size => 41; type Bits_42 is mod 2**42 with Size => 42; type Bits_43 is mod 2**43 with Size => 43; type Bits_44 is mod 2**44 with Size => 44; type Bits_45 is mod 2**45 with Size => 45; type Bits_46 is mod 2**46 with Size => 46; type Bits_47 is mod 2**47 with Size => 47; type Bits_48 is mod 2**48 with Size => 48; type Bits_49 is mod 2**49 with Size => 49; type Bits_50 is mod 2**50 with Size => 50; type Bits_51 is mod 2**51 with Size => 51; type Bits_52 is mod 2**52 with Size => 52; type Bits_53 is mod 2**53 with Size => 53; type Bits_54 is mod 2**54 with Size => 54; type Bits_55 is mod 2**55 with Size => 55; type Bits_56 is mod 2**56 with Size => 56; type Bits_57 is mod 2**57 with Size => 57; type Bits_58 is mod 2**58 with Size => 58; type Bits_59 is mod 2**59 with Size => 59; type Bits_60 is mod 2**60 with Size => 60; type Bits_61 is mod 2**61 with Size => 61; type Bits_62 is mod 2**62 with Size => 62; type Bits_63 is mod 2**63 with Size => 63; subtype Bits_64 is Interfaces.Unsigned_64; type Byte_Array is array (Natural range <>) of Bits_8; end DW1000.Types;
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with Interfaces; package DW1000.Types with SPARK_Mode => On is type Bits_1 is mod 2**1 with Size => 1; type Bits_2 is mod 2**2 with Size => 2; type Bits_3 is mod 2**3 with Size => 3; type Bits_4 is mod 2**4 with Size => 4; type Bits_5 is mod 2**5 with Size => 5; type Bits_6 is mod 2**6 with Size => 6; type Bits_7 is mod 2**7 with Size => 7; subtype Bits_8 is Interfaces.Unsigned_8; type Bits_9 is mod 2**9 with Size => 9; type Bits_10 is mod 2**10 with Size => 10; type Bits_11 is mod 2**11 with Size => 11; type Bits_12 is mod 2**12 with Size => 12; type Bits_13 is mod 2**13 with Size => 13; type Bits_14 is mod 2**14 with Size => 14; type Bits_15 is mod 2**15 with Size => 15; subtype Bits_16 is Interfaces.Unsigned_16; type Bits_17 is mod 2**17 with Size => 17; type Bits_18 is mod 2**18 with Size => 18; type Bits_19 is mod 2**19 with Size => 19; type Bits_20 is mod 2**20 with Size => 20; type Bits_21 is mod 2**21 with Size => 21; type Bits_22 is mod 2**22 with Size => 22; type Bits_23 is mod 2**23 with Size => 23; type Bits_24 is mod 2**24 with Size => 24; type Bits_25 is mod 2**25 with Size => 25; type Bits_26 is mod 2**26 with Size => 26; type Bits_27 is mod 2**27 with Size => 27; type Bits_28 is mod 2**28 with Size => 28; type Bits_29 is mod 2**29 with Size => 29; type Bits_30 is mod 2**30 with Size => 30; type Bits_31 is mod 2**31 with Size => 31; subtype Bits_32 is Interfaces.Unsigned_32; type Bits_33 is mod 2**33 with Size => 33; type Bits_34 is mod 2**34 with Size => 34; type Bits_35 is mod 2**35 with Size => 35; type Bits_36 is mod 2**36 with Size => 36; type Bits_37 is mod 2**37 with Size => 37; type Bits_38 is mod 2**38 with Size => 38; type Bits_39 is mod 2**39 with Size => 39; type Bits_40 is mod 2**40 with Size => 40; type Bits_41 is mod 2**41 with Size => 41; type Bits_42 is mod 2**42 with Size => 42; type Bits_43 is mod 2**43 with Size => 43; type Bits_44 is mod 2**44 with Size => 44; type Bits_45 is mod 2**45 with Size => 45; type Bits_46 is mod 2**46 with Size => 46; type Bits_47 is mod 2**47 with Size => 47; type Bits_48 is mod 2**48 with Size => 48; type Bits_49 is mod 2**49 with Size => 49; type Bits_50 is mod 2**50 with Size => 50; type Bits_51 is mod 2**51 with Size => 51; type Bits_52 is mod 2**52 with Size => 52; type Bits_53 is mod 2**53 with Size => 53; type Bits_54 is mod 2**54 with Size => 54; type Bits_55 is mod 2**55 with Size => 55; type Bits_56 is mod 2**56 with Size => 56; type Bits_57 is mod 2**57 with Size => 57; type Bits_58 is mod 2**58 with Size => 58; type Bits_59 is mod 2**59 with Size => 59; type Bits_60 is mod 2**60 with Size => 60; type Bits_61 is mod 2**61 with Size => 61; type Bits_62 is mod 2**62 with Size => 62; type Bits_63 is mod 2**63 with Size => 63; subtype Bits_64 is Interfaces.Unsigned_64; subtype Index is Natural range 0 .. Natural'Last - 1; type Byte_Array is array (Index range <>) of Bits_8; end DW1000.Types;
Reduce maximum Byte_Array length to avoid overflow with 'Length attribute
Reduce maximum Byte_Array length to avoid overflow with 'Length attribute When a subprogram takes an unconstrained Byte_Array as a parameter and references its 'Length attribute it is possible that in the case of the largest possible array ('First = 0 and 'Last = 2**31 - 1) then 'Length is equal to 2**31 which is 1 past the maximum range supported by the Natural type (on a 32-bit ARM microcontroller, at least) which is now detected by SPARK Discovery 2017. This commit constrains the index range of the Byte_Array type by 1 to allow all possible 'Length values to fit inside the Natural type.
Ada
mit
damaki/DW1000
b4a7b9f5c00a60ff5a00e5ba2f20c80c80943350
samples/facebook.adb
samples/facebook.adb
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- 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.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Objects; with Util.Http.Clients; with Util.Http.Clients.Web; with Util.Http.Rest; with Util.Serialize.IO.JSON; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.Web.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User ("https://graph.facebook.com/" & URI, Person_Mapping'Unchecked_Access, P'Unchecked_Access); Print (P); end; end loop; end Facebook;
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- 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.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Http.Clients.Web; with Util.Http.Rest; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.Web.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User ("https://graph.facebook.com/" & URI, Person_Mapping'Unchecked_Access, P'Unchecked_Access); Print (P); end; end loop; end Facebook;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
a4d779a631b6b9161b2470d870cbfd1689dbe9d4
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the address range and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Declare a new Print_Field procedure to print a range of address
Declare a new Print_Field procedure to print a range of address
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4a63335706e975a406912fa8cfb408c7f94c8f34
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); end Finalize; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Implement Find_Region and Find_Symbol functions for the Resolver_Type interface
Implement Find_Region and Find_Symbol functions for the Resolver_Type interface
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1a7198873717ed484f33d677e0d5eb9489caa184
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("mat>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Properties; with Util.Log.Loggers; with MAT.Commands; with MAT.Interrupts; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (MAT.Frames.Targets.Target_Frames'Class, MAT.Frames.Targets.Target_Frames_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- Configure the log managers used by mat. procedure Initialize_Logs (Path : in String); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); Free (Target.Frames); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- Find the process instance from the process ID. -- ------------------------------ function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- Convert the string to a socket address. The string can have two forms: -- port -- host:port -- ------------------------------ function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-d path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-d path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Configure the log managers used by mat. -- ------------------------------ procedure Initialize_Logs (Path : in String) is Props : Util.Properties.Manager; begin begin Props.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => -- Default log configuration. Props.Set ("log4j.rootCategory", "INFO,console,mat"); Props.Set ("log4j.appender.console", "Console"); Props.Set ("log4j.appender.console.level", "WARN"); Props.Set ("log4j.appender.console.layout", "level-message"); Props.Set ("log4j.appender.mat", "File"); Props.Set ("log4j.appender.mat.File", "mat.log"); end; Util.Log.Loggers.Initialize (Props); end Initialize_Logs; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Initialize_Logs ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: d:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 'd' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ procedure Interactive (Target : in out MAT.Targets.Target_Type) is begin MAT.Interrupts.Install; loop declare Line : constant String := Readline.Get_Line ("mat>"); begin MAT.Interrupts.Clear; MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Change -s <path> option into -d <path> option
Change -s <path> option into -d <path> option
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c862538eb7ec319f8a1a9e94e5ab26b158600e9c
awa/src/awa-components-wikis.ads
awa/src/awa-components-wikis.ads
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- 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.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with AWA.Wikis.Parsers; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return AWA.Wikis.Parsers.Wiki_Syntax_Type; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- 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.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Parsers; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); end AWA.Components.Wikis;
Use the Ada Wiki library
Use the Ada Wiki library
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
77616f954547028c7790916569d5927e3b8c956e
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile"); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); T.Manager.Load (From => T.Id, Into => Data); T.Assert (Data.Is_Null, "A non null blob returned by load"); end Test_Delete_Storage; end AWA.Storages.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Util.Test_Caller; with ADO; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Tests.Helpers.Users; package body AWA.Storages.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Storages.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save", Test_Create_Storage'Access); Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete", Test_Delete_Storage'Access); end Add_Tests; -- ------------------------------ -- Save something in a storage element and keep track of the store id in the test <b>Id</b>. -- ------------------------------ procedure Save (T : in out Test) is Store : AWA.Storages.Models.Storage_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Save (Into => Store, Path => "Makefile", Storage => AWA.Storages.Models.DATABASE); T.Assert (not Store.Is_Null, "Storage object should not be null"); T.Id := Store.Get_Id; T.Assert (T.Id > 0, "Invalid storage identifier"); end Save; -- ------------------------------ -- Load the storage element refered to by the test <b>Id</b>. -- ------------------------------ procedure Load (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Data : ADO.Blob_Ref; begin T.Manager := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (T.Manager /= null, "Null storage manager"); T.Manager.Load (From => T.Id, Into => Data); T.Assert (not Data.Is_Null, "Null blob returned by load"); T.Assert (Data.Value.Len > 100, "Invalid length for the blob data"); end Load; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Load; end Test_Create_Storage; -- ------------------------------ -- Test deletion of a storage object -- ------------------------------ procedure Test_Delete_Storage (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Data : ADO.Blob_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Save; T.Manager.Delete (T.Id); T.Manager.Load (From => T.Id, Into => Data); T.Assert (Data.Is_Null, "A non null blob returned by load"); end Test_Delete_Storage; end AWA.Storages.Services.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
37917bb9370ede46abcb209ab7235462d3a90875
lumen.ads
lumen.ads
-- Lumen -- A simple graphical user interface library based on OpenGL -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 2010 -- Lumen would not be possible without the support and contributions of a cast -- of thousands, including and primarily Rod Kay. -- This code is covered by the ISC License: -- -- Copyright (c) 2010, NiEstu -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY -- SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -- IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. package Lumen is pragma Pure (Lumen); end Lumen;
-- Lumen -- A simple graphical user interface library based on OpenGL -- -- Chip Richards, NiEstu, Phoenix AZ, Spring 2010 -- Lumen would not be possible without the support and contributions of a cast -- of thousands, including and primarily Rod Kay. -- This code is covered by the ISC License: -- -- Copyright (c) 2010, NiEstu -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- The software is provided "as is" and the author disclaims all warranties -- with regard to this software including all implied warranties of -- merchantability and fitness. In no event shall the author be liable for any -- special, direct, indirect, or consequential damages or any damages -- whatsoever resulting from loss of use, data or profits, whether in an -- action of contract, negligence or other tortious action, arising out of or -- in connection with the use or performance of this software. package Lumen is pragma Pure (Lumen); end Lumen;
Change license text to mixed case instead of SHOUTING it
Change license text to mixed case instead of SHOUTING it
Ada
isc
darkestkhan/lumen2,darkestkhan/lumen
4da4f785cf046c502e4959c7b5ea9c27307bb3e5
src/asf-converters-dates.ads
src/asf-converters-dates.ads
----------------------------------------------------------------------- -- asf-converters-dates -- Date Converters -- 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.Beans.Objects; with ASF.Components.Base; with ASF.Contexts.Faces; -- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object -- into a localized representation. -- -- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime> -- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method) package ASF.Converters.Dates is -- ------------------------------ -- Converter -- ------------------------------ -- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar -- into a printable date representation. It translates a string into an Ada Calendar time. -- Unlike the Java implementation, the instance will be shared by multiple -- views and requests. type Date_Converter is new Converter with null record; type Date_Converter_Access is access all Date_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_String (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String; -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_Object (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object; -- Get the date format pattern that must be used for formatting a date on the given component. function Get_Pattern (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class) return String; end ASF.Converters.Dates;
----------------------------------------------------------------------- -- asf-converters-dates -- Date Converters -- Copyright (C) 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 Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Locales; with ASF.Components.Base; with ASF.Contexts.Faces; with ASF.Locales; -- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object -- into a localized representation. -- -- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime> -- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method) package ASF.Converters.Dates is type Style_Type is (DEFAULT, SHORT, MEDIUM, LONG, FULL); type Format_Type is (DATE, TIME, BOTH, CONVERTER_PATTERN, COMPONENT_FORMAT); -- ------------------------------ -- Converter -- ------------------------------ -- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar -- into a printable date representation. It translates a string into an Ada Calendar time. -- Unlike the Java implementation, the instance will be shared by multiple -- views and requests. type Date_Converter is new Converter with private; type Date_Converter_Access is access all Date_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_String (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String; -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. function To_Object (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object; -- Get the date format pattern that must be used for formatting a date on the given component. function Get_Pattern (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Bundle : in ASF.Locales.Bundle; Component : in ASF.Components.Base.UIComponent'Class) return String; -- Get the locale that must be used to format the date. function Get_Locale (Convert : in Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Create a date converter. function Create_Date_Converter (Date : in Style_Type; Time : in Style_Type; Format : in Format_Type; Locale : in String; Pattern : in String) return Date_Converter_Access; private type Date_Converter is new Converter with record Date_Style : Style_Type := DEFAULT; Time_Style : Style_Type := DEFAULT; Format : Format_Type; Locale : Util.Locales.Locale; Pattern : Ada.Strings.Unbounded.Unbounded_String; end record; end ASF.Converters.Dates;
Add support for various date conversion formats defined in JSR-314 - new type Style_Type to define the pre-defined date and time formats - new type Format_Type to define the global date+time or pattern format - new operation Get_Locale to return the date conversion target locale - new function Create_Date_Converter to build the date converter instance - define in the Date_Converter instance the date, time, locale and pattern
Add support for various date conversion formats defined in JSR-314 - new type Style_Type to define the pre-defined date and time formats - new type Format_Type to define the global date+time or pattern format - new operation Get_Locale to return the date conversion target locale - new function Create_Date_Converter to build the date converter instance - define in the Date_Converter instance the date, time, locale and pattern
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f48e724e826c17ed842bce25382b35dc8db44ac3
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; In_Table : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser'Class; Token : out Wiki.Strings.WChar); pragma Inline (Peek); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Add In_Table in the parser type
Add In_Table in the parser type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ff54ffa45cb90ac74295545393d54a598a312529
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare the Append and Length operation on UString
Declare the Append and Length operation on UString
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
8e68050f2aae977769609d127e784e42381a4387
src/util-log-locations.ads
src/util-log-locations.ads
----------------------------------------------------------------------- -- util-log-locations -- General purpose source file location -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Log.Locations is -- ------------------------------ -- Source line information -- ------------------------------ type File_Info (<>) is limited private; type File_Info_Access is access all File_Info; -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access; -- Get the relative path name function Relative_Path (File : in File_Info) return String; type Line_Info is private; -- Get the line number function Line (Info : in Line_Info) return Natural; -- Get the column number function Column (Info : in Line_Info) return Natural; -- Get the source file function File (Info : in Line_Info) return String; -- Compare the two source location. The comparison is made on: -- o the source file, -- o the line number, -- o the column. function "<" (Left, Right : in Line_Info) return Boolean; -- Create a source line information. function Create_Line_Info (File : in File_Info_Access; Line : in Natural; Column : in Natural := 0) return Line_Info; -- Get a printable representation of the line information using -- the format: -- <path>:<line>[:<column>] -- The path can be reported as relative or absolute path. -- The column is optional and reported by default. function To_String (Info : in Line_Info; Relative : in Boolean := True; Column : in Boolean := True) return String; private pragma Inline (Line); pragma Inline (File); type File_Info (Length : Natural) is limited record Relative_Pos : Natural; Path : String (1 .. Length); end record; NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0); type Line_Info is record Line : Natural := 0; Column : Natural := 0; File : File_Info_Access := NO_FILE'Access; end record; end Util.Log.Locations;
----------------------------------------------------------------------- -- util-log-locations -- General purpose source file location -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Log.Locations is -- ------------------------------ -- Source line information -- ------------------------------ type File_Info (<>) is limited private; type File_Info_Access is access all File_Info; -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access; -- Get the relative path name function Relative_Path (File : in File_Info) return String; type Line_Info is private; -- Get the line number function Line (Info : in Line_Info) return Natural; -- Get the column number function Column (Info : in Line_Info) return Natural; -- Get the source file function File (Info : in Line_Info) return String; -- Compare the two source location. The comparison is made on: -- o the source file, -- o the line number, -- o the column. function "<" (Left, Right : in Line_Info) return Boolean; -- Create a source line information. function Create_Line_Info (File : in File_Info_Access; Line : in Natural; Column : in Natural := 0) return Line_Info; -- Get a printable representation of the line information using -- the format: -- <path>:<line>[:<column>] -- The path can be reported as relative or absolute path. -- The column is optional and reported by default. function To_String (Info : in Line_Info; Relative : in Boolean := True; Column : in Boolean := True) return String; private pragma Inline (Line); pragma Inline (File); type File_Info (Length : Natural) is limited record Relative_Pos : Natural; Path : String (1 .. Length); end record; NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 1); type Line_Info is record Line : Natural := 0; Column : Natural := 0; File : File_Info_Access := NO_FILE'Access; end record; end Util.Log.Locations;
Fix relative_pos for the empty file
Fix relative_pos for the empty file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
be3c37804f0c6736ad87f05e41eda6aa1a014eb0
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
Letractively/ada-security
10f3ddd607dc237bc2b87ef4cd6dbccd3f582714
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- 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); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Html_Renderer); -- 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 (Document : in out Html_Renderer); -- 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); -- 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); -- Add a link. procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- 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); procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- 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); -- Add a section header in the document. procedure Add_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Html_Renderer); -- 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); -- 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); -- Add a link. procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- 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); procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; end Wiki.Render.Html;
Remove Add_Paragraph procedure
Remove Add_Paragraph procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ef3fdb8113a60947a0710e406939e311754152fe
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; package ADO.Queries is type Query_File; type Query_File_Access is access all Query_File; type Query_Definition; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String; -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). Query : Query_Info_Ref_Access; end record; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; end record; private type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 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.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; with Interfaces; with Ada.Strings.Unbounded; package ADO.Queries is type Query_File; type Query_File_Access is access all Query_File; type Query_Definition; type Query_Definition_Access is access all Query_Definition; type Query_Info is limited private; type Query_Info_Access is access all Query_Info; type Query_Info_Ref_Access is private; Null_Query_Info_Ref : constant Query_Info_Ref_Access; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String; -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). Query : Query_Info_Ref_Access; end record; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.String_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; end record; private type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; Null_Query_Info_Ref : constant Query_Info_Ref_Access := null; end ADO.Queries;
Declare the Set_SQL procedure
Declare the Set_SQL procedure
Ada
apache-2.0
stcarrez/ada-ado
1709a8a07e355ec59c06760dcdfb87e6f6ae6727
src/ado-sql.adb
src/ado-sql.adb
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 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. ----------------------------------------------------------------------- -- Utilities for creating SQL queries and statements. package body ADO.SQL is -- -------------------- -- Buffer -- -------------------- -- -------------------- -- Clear the SQL buffer. -- -------------------- procedure Clear (Target : in out Buffer) is begin Target.Buf := To_Unbounded_String (""); end Clear; -- -------------------- -- Append an SQL extract into the buffer. -- -------------------- procedure Append (Target : in out Buffer; SQL : in String) is begin Append (Target.Buf, SQL); end Append; -- -------------------- -- Append a name in the buffer and escape that -- name if this is a reserved keyword. -- -------------------- procedure Append_Name (Target : in out Buffer; Name : in String) is use type ADO.Drivers.Dialects.Dialect_Access; Dialect : constant ADO.Drivers.Dialects.Dialect_Access := Target.Get_Dialect; begin if Dialect /= null and then Dialect.Is_Reserved (Name) then declare Quote : constant Character := Dialect.Get_Identifier_Quote; begin Append (Target.Buf, Quote); Append (Target.Buf, Name); Append (Target.Buf, Quote); end; else Append (Target.Buf, Name); end if; end Append_Name; -- -------------------- -- Append a string value in the buffer and -- escape any special character if necessary. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in String) is begin Append (Target.Buf, Value); end Append_Value; -- -------------------- -- Append a string value in the buffer and -- escape any special character if necessary. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String) is begin Append (Target.Buf, Value); end Append_Value; -- -------------------- -- Append the integer value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Long_Integer) is S : constant String := Long_Integer'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Append the integer value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Integer) is S : constant String := Integer'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Append the identifier value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Identifier) is S : constant String := Identifier'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Get the SQL string that was accumulated in the buffer. -- -------------------- function To_String (From : in Buffer) return String is begin return To_String (From.Buf); end To_String; -- -------------------- -- Clear the query object. -- -------------------- overriding procedure Clear (Target : in out Query) is begin ADO.Parameters.List (Target).Clear; Target.Join.Clear; Target.Filter.Clear; Target.SQL.Clear; end Clear; -- -------------------- -- Set the SQL dialect description object. -- -------------------- procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access) is begin ADO.Parameters.Abstract_List (Target).Set_Dialect (D); Set_Dialect (Target.SQL, D); Set_Dialect (Target.Filter, D); Set_Dialect (Target.Join, D); end Set_Dialect; procedure Set_Filter (Target : in out Query; Filter : in String) is begin Target.Filter.Buf := To_Unbounded_String (Filter); end Set_Filter; function Get_Filter (Source : in Query) return String is begin if Source.Filter.Buf = Null_Unbounded_String then return ""; else return To_String (Source.Filter.Buf); end if; end Get_Filter; function Has_Filter (Source : in Query) return Boolean is begin return Source.Filter.Buf /= Null_Unbounded_String and Length (Source.Filter.Buf) > 0; end Has_Filter; -- -------------------- -- Set the join condition. -- -------------------- procedure Set_Join (Target : in out Query; Join : in String) is begin Target.Join.Buf := To_Unbounded_String (Join); end Set_Join; -- -------------------- -- Returns true if there is a join condition -- -------------------- function Has_Join (Source : in Query) return Boolean is begin return Source.Join.Buf /= Null_Unbounded_String and Length (Source.Join.Buf) > 0; end Has_Join; -- -------------------- -- Get the join condition -- -------------------- function Get_Join (Source : in Query) return String is begin if Source.Join.Buf = Null_Unbounded_String then return ""; else return To_String (Source.Join.Buf); end if; end Get_Join; -- -------------------- -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. -- -------------------- procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class) is begin ADO.Parameters.List (Params).Set_Parameters (From); if From in Query'Class then declare L : constant Query'Class := Query'Class (From); begin Params.Filter := L.Filter; Params.Join := L.Join; end; end if; end Set_Parameters; -- -------------------- -- Expand the parameters into the query and return the expanded SQL query. -- -------------------- function Expand (Source : in Query) return String is begin return ADO.Parameters.Abstract_List (Source).Expand (To_String (Source.SQL.Buf)); end Expand; procedure Add_Field (Update : in out Update_Query'Class; Name : in String) is begin Update.Pos := Update.Pos + 1; if Update.Pos > 1 then Append (Target => Update.Set_Fields, SQL => ","); Append (Target => Update.Fields, SQL => ","); end if; Append_Name (Target => Update.Set_Fields, Name => Name); if Update.Is_Update_Stmt then Append (Target => Update.Set_Fields, SQL => " = ?"); end if; Append (Target => Update.Fields, SQL => "?"); end Add_Field; -- ------------------------------ -- Set the SQL dialect description object. -- ------------------------------ procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access) is begin Target.Set_Fields.Set_Dialect (D); Target.Fields.Set_Dialect (D); Query (Target).Set_Dialect (D); end Set_Dialect; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- ------------------------------ procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Integer (Value)); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- ------------------------------ procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. -- ------------------------------ procedure Save_Null_Field (Update : in out Update_Query; Name : in String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Null_Param (Position => Update.Pos); end Save_Null_Field; -- -------------------- -- Check if the update/insert query has some fields to update. -- -------------------- function Has_Save_Fields (Update : in Update_Query) return Boolean is begin return Update.Pos > 0; end Has_Save_Fields; procedure Set_Insert_Mode (Update : in out Update_Query) is begin Update.Is_Update_Stmt := False; end Set_Insert_Mode; procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False) is begin if Mode then Append (Target => Update.SQL, SQL => To_String (Update.Fields.Buf)); else Append (Target => Update.SQL, SQL => To_String (Update.Set_Fields.Buf)); end if; end Append_Fields; end ADO.SQL;
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- Utilities for creating SQL queries and statements. package body ADO.SQL is -- -------------------- -- Buffer -- -------------------- -- -------------------- -- Clear the SQL buffer. -- -------------------- procedure Clear (Target : in out Buffer) is begin Target.Buf := To_Unbounded_String (""); end Clear; -- -------------------- -- Append an SQL extract into the buffer. -- -------------------- procedure Append (Target : in out Buffer; SQL : in String) is begin Append (Target.Buf, SQL); end Append; -- -------------------- -- Append a name in the buffer and escape that -- name if this is a reserved keyword. -- -------------------- procedure Append_Name (Target : in out Buffer; Name : in String) is use type ADO.Drivers.Dialects.Dialect_Access; Dialect : constant ADO.Drivers.Dialects.Dialect_Access := Target.Get_Dialect; begin if Dialect /= null and then Dialect.Is_Reserved (Name) then declare Quote : constant Character := Dialect.Get_Identifier_Quote; begin Append (Target.Buf, Quote); Append (Target.Buf, Name); Append (Target.Buf, Quote); end; else Append (Target.Buf, Name); end if; end Append_Name; -- -------------------- -- Append a string value in the buffer and -- escape any special character if necessary. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in String) is begin Append (Target.Buf, Value); end Append_Value; -- -------------------- -- Append a string value in the buffer and -- escape any special character if necessary. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String) is begin Append (Target.Buf, Value); end Append_Value; -- -------------------- -- Append the integer value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Long_Integer) is S : constant String := Long_Integer'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Append the integer value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Integer) is S : constant String := Integer'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Append the identifier value in the buffer. -- -------------------- procedure Append_Value (Target : in out Buffer; Value : in Identifier) is S : constant String := Identifier'Image (Value); begin Append (Target.Buf, S (S'First + 1 .. S'Last)); end Append_Value; -- -------------------- -- Get the SQL string that was accumulated in the buffer. -- -------------------- function To_String (From : in Buffer) return String is begin return To_String (From.Buf); end To_String; -- -------------------- -- Clear the query object. -- -------------------- overriding procedure Clear (Target : in out Query) is begin ADO.Parameters.List (Target).Clear; Target.Join.Clear; Target.Filter.Clear; Target.SQL.Clear; end Clear; -- -------------------- -- Set the SQL dialect description object. -- -------------------- procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access) is begin ADO.Parameters.Abstract_List (Target).Set_Dialect (D); Set_Dialect (Target.SQL, D); Set_Dialect (Target.Filter, D); Set_Dialect (Target.Join, D); end Set_Dialect; procedure Set_Filter (Target : in out Query; Filter : in String) is begin Target.Filter.Buf := To_Unbounded_String (Filter); end Set_Filter; function Get_Filter (Source : in Query) return String is begin if Source.Filter.Buf = Null_Unbounded_String then return ""; else return To_String (Source.Filter.Buf); end if; end Get_Filter; function Has_Filter (Source : in Query) return Boolean is begin return Source.Filter.Buf /= Null_Unbounded_String and Length (Source.Filter.Buf) > 0; end Has_Filter; -- -------------------- -- Set the join condition. -- -------------------- procedure Set_Join (Target : in out Query; Join : in String) is begin Target.Join.Buf := To_Unbounded_String (Join); end Set_Join; -- -------------------- -- Returns true if there is a join condition -- -------------------- function Has_Join (Source : in Query) return Boolean is begin return Source.Join.Buf /= Null_Unbounded_String and Length (Source.Join.Buf) > 0; end Has_Join; -- -------------------- -- Get the join condition -- -------------------- function Get_Join (Source : in Query) return String is begin if Source.Join.Buf = Null_Unbounded_String then return ""; else return To_String (Source.Join.Buf); end if; end Get_Join; -- -------------------- -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. -- -------------------- procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class) is begin ADO.Parameters.List (Params).Set_Parameters (From); if From in Query'Class then declare L : constant Query'Class := Query'Class (From); begin Params.Filter := L.Filter; Params.Join := L.Join; end; end if; end Set_Parameters; -- -------------------- -- Expand the parameters into the query and return the expanded SQL query. -- -------------------- function Expand (Source : in Query) return String is begin return ADO.Parameters.Abstract_List (Source).Expand (To_String (Source.SQL.Buf)); end Expand; procedure Add_Field (Update : in out Update_Query'Class; Name : in String) is begin Update.Pos := Update.Pos + 1; if Update.Pos > 1 then Append (Target => Update.Set_Fields, SQL => ","); Append (Target => Update.Fields, SQL => ","); end if; Append_Name (Target => Update.Set_Fields, Name => Name); if Update.Is_Update_Stmt then Append (Target => Update.Set_Fields, SQL => " = ?"); end if; Append (Target => Update.Fields, SQL => "?"); end Add_Field; -- ------------------------------ -- Set the SQL dialect description object. -- ------------------------------ procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access) is begin Target.Set_Fields.Set_Dialect (D); Target.Fields.Set_Dialect (D); Query (Target).Set_Dialect (D); end Set_Dialect; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- ------------------------------ procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Float) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Integer (Value)); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Add_Param (Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- -------------------- -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- -------------------- procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. -- ------------------------------ procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value); end Save_Field; -- ------------------------------ -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. -- ------------------------------ procedure Save_Null_Field (Update : in out Update_Query; Name : in String) is begin Update.Add_Field (Name => Name); Update_Query'Class (Update).Bind_Null_Param (Position => Update.Pos); end Save_Null_Field; -- -------------------- -- Check if the update/insert query has some fields to update. -- -------------------- function Has_Save_Fields (Update : in Update_Query) return Boolean is begin return Update.Pos > 0; end Has_Save_Fields; procedure Set_Insert_Mode (Update : in out Update_Query) is begin Update.Is_Update_Stmt := False; end Set_Insert_Mode; procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False) is begin if Mode then Append (Target => Update.SQL, SQL => To_String (Update.Fields.Buf)); else Append (Target => Update.SQL, SQL => To_String (Update.Set_Fields.Buf)); end if; end Append_Fields; end ADO.SQL;
Implement Save_Field with a Long_Float
Implement Save_Field with a Long_Float
Ada
apache-2.0
stcarrez/ada-ado
a7a1f4888d12c7bda75e0480bbde6226cafb66bf
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * Discovery to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * Verify to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Openid.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback CB. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
2cf1bb6b615cdbda9c0e9edd803e7f6c0d0219dd
src/sys/os-linux64/util-systems-constants.ads
src/sys/os-linux64/util-systems-constants.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000100#; O_EXCL : constant Interfaces.C.int := 8#000200#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#002000#; O_CLOEXEC : constant Interfaces.C.int := 8#2000000#; O_SYNC : constant Interfaces.C.int := 8#4010000#; O_DIRECT : constant Interfaces.C.int := 0; O_NONBLOCK : constant Interfaces.C.int := 8#004000#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#000004#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000010#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#000000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := "-ldl"; end Util.Systems.Constants;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#000100#; O_EXCL : constant Interfaces.C.int := 8#000200#; O_TRUNC : constant Interfaces.C.int := 8#001000#; O_APPEND : constant Interfaces.C.int := 8#002000#; O_CLOEXEC : constant Interfaces.C.int := 8#2000000#; O_SYNC : constant Interfaces.C.int := 8#4010000#; O_DIRECT : constant Interfaces.C.int := 0; O_NONBLOCK : constant Interfaces.C.int := 8#004000#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#000004#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000010#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#000000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := "-ldl"; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
Declare SYMBOL_PREFIX
Declare SYMBOL_PREFIX
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a2b19ff6c416d43e439c467a59282f0dd1bf5f3e
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- 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 Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString; -- 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; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- 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)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); 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 Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. Attributes are used for -- the Wiki document representation to describe the HTML attributes that were parsed and -- several parameters that describe Wiki content (links, ...). -- -- The Wiki filters and Wiki plugins have access to the attributes before they are added -- to the Wiki document. They can check them or modify them according to their needs. -- -- The Wiki renderers use the attributes to render the final HTML content. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString; -- 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; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- 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)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d3f67947ce3f060fbf4a3fa85aeb2e663d37734f
regtests/ado-statements-tests.adb
regtests/ado-statements-tests.adb
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is use Util.Tests; procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
Remove unecessary use clause
Remove unecessary use clause
Ada
apache-2.0
stcarrez/ada-ado
1d4e5de6dd4c9718bdb892ced9b2309415932435
awa/src/awa-blogs-beans.adb
awa/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; overriding function Copy (Bean : in Blog_Bean) return Blog_Bean is pragma Unreferenced (Bean); Ref : Blog_Bean; begin return Ref; end Copy; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_URI, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => To_String (Bean.Title), Text => To_String (Bean.Text)); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_URI (Util.Beans.Objects.To_Unbounded_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_URI; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; overriding function Copy (Bean : in Blog_Bean) return Blog_Bean is pragma Unreferenced (Bean); Ref : Blog_Bean; begin return Ref; end Copy; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_URI, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_URI (Util.Beans.Objects.To_Unbounded_String (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_URI; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
Fix updating the blog post title and content
Fix updating the blog post title and content
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
e970a5b9c91db98747ad30f2c1a194fdab66c3cf
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- 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.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); Result : Boolean; begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; Context.Has_Permission (Perm, Result); if not Result then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); Result : Boolean; begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; Context.Has_Permission (Perm, Result); if not Result then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
Remove Finish_Config procedure
Remove Finish_Config procedure
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
b92bccd7ab3b96d73c78b48966ad152cf9aa628d
src/asf-components-html-factory.ads
src/asf-components-html-factory.ads
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Factory; package ASF.Components.Html.Factory is use ASF; -- Get the HTML component factory. function Definition return ASF.Factory.Factory_Bindings_Access; end ASF.Components.Html.Factory;
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010, 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 ASF.Factory; package ASF.Components.Html.Factory is -- Register the HTML component factory. procedure Register (Factory : in out ASF.Factory.Component_Factory); end ASF.Components.Html.Factory;
Change the Definition function into a Register procedure
Change the Definition function into a Register procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
5214c28a6c1be39bafed39001de2b7d0504e5e57
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- 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 Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Databases; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; use type ADO.Databases.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Conn : constant ADO.Databases.Connection'Class := DB.Get_Connection; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (Conn.Get_Status = ADO.Databases.OPEN, "The database connection is open"); T.Assert (DB.Get_Status = ADO.Databases.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
Check the database connection in the Test_Create_Save unit test
Check the database connection in the Test_Create_Save unit test
Ada
apache-2.0
stcarrez/ada-ado
e178f56cc7f1b0af33f9fef081cccef380f5e2f6
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Number := Table.Members.Get_Count; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the table unique name. -- ------------------------------ overriding function Get_Name (From : in Table_Definition) return String is begin return From.Get_Attribute ("table"); end Get_Name; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; package body Gen.Model.Tables is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" and From.Type_Mapping /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; Name : constant String := To_String (From.Type_Name); begin if From.Type_Mapping /= null then return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if From.Type_Mapping /= null then return To_String (From.Type_Mapping.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is begin O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Get the table unique name. -- ------------------------------ overriding function Get_Name (From : in Table_Definition) return String is begin return From.Get_Attribute ("table"); end Get_Name; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Set the SQL name when building the column
Set the SQL name when building the column
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
927d878798138cde330f93141d25ff24129758be
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); 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. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); 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. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Implement the new function Get_URL_Policy
Implement the new function Get_URL_Policy
Ada
apache-2.0
stcarrez/ada-security
0da488961fc5717eac183e1a2ecdc77bdf1d716e
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
Rename package URLs and the permission URL_Permission
Rename package URLs and the permission URL_Permission
Ada
apache-2.0
stcarrez/ada-security
846fb5bf3336b7186148e62bf6e0414fda648095
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL. -- -- URI : constant String := ...; -- Perm : constant Policies.URLs.URI_Permission (URI'Length) -- := URI_Permission '(Len => URI'Length, URI => URI); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.Urls is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.Urls;
Remove Finish_Config which is not necessary
Remove Finish_Config which is not necessary
Ada
apache-2.0
stcarrez/ada-security
3ba9a4d5472c34754232ca9f0faf9f8389cfe5ed
src/core/util-executors.ads
src/core/util-executors.ads
----------------------------------------------------------------------- -- util-executors -- Execute work that is queued -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Exceptions; private with Util.Concurrent.Fifos; -- == Executors == -- The `Util.Executors` generic package defines a queue of work that will be executed -- by one or several tasks. The `Work_Type` describes the type of the work and the -- `Execute` procedure will be called by the task to execute the work. After instantiation -- of the package, an instance of the `Executor_Manager` is created with a number of desired -- tasks. The tasks are then started by calling the `Start` procedure. -- -- A work object is added to the executor's queue by using the `Execute` procedure. -- The work object is added in a concurrent fifo queue. One of the task managed by the -- executor manager will pick the work object and run it. -- generic type Work_Type is private; with procedure Execute (Work : in out Work_Type); with procedure Error (Work : in out Work_Type; Err : in Ada.Exceptions.Exception_Occurrence) is null; Default_Queue_Size : Positive := 32; package Util.Executors is use Ada.Finalization; type Executor_Manager (Count : Positive) is limited new Limited_Controlled with private; type Executor_Manager_Access is access all Executor_Manager'Class; overriding procedure Initialize (Manager : in out Executor_Manager); -- Execute the work through the executor. procedure Execute (Manager : in out Executor_Manager; Work : in Work_Type); -- Start the executor tasks. procedure Start (Manager : in out Executor_Manager); -- Stop the tasks and wait for their completion. procedure Stop (Manager : in out Executor_Manager); -- Set the work queue size. procedure Set_Queue_Size (Manager : in out Executor_Manager; Capacity : in Positive); -- Stop and release the executor. overriding procedure Finalize (Manager : in out Executor_Manager); private type Work_Info is record Work : Work_Type; Done : Boolean := False; end record; package Work_Queue is new Util.Concurrent.Fifos (Element_Type => Work_Info, Default_Size => Default_Queue_Size, Clear_On_Dequeue => True); task type Worker_Task is entry Start (Manager : in Executor_Manager_Access); end Worker_Task; type Worker_Task_Array is array (Positive range <>) of Worker_Task; type Executor_Manager (Count : Positive) is limited new Limited_Controlled with record Self : Executor_Manager_Access; Queue : Work_Queue.Fifo; Workers : Worker_Task_Array (1 .. Count); end record; end Util.Executors;
----------------------------------------------------------------------- -- util-executors -- Execute work that is queued -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Exceptions; private with Util.Concurrent.Fifos; -- == Executors == -- The `Util.Executors` generic package defines a queue of work that will be executed -- by one or several tasks. The `Work_Type` describes the type of the work and the -- `Execute` procedure will be called by the task to execute the work. After instantiation -- of the package, an instance of the `Executor_Manager` is created with a number of desired -- tasks. The tasks are then started by calling the `Start` procedure. -- -- A work object is added to the executor's queue by using the `Execute` procedure. -- The work object is added in a concurrent fifo queue. One of the task managed by the -- executor manager will pick the work object and run it. -- generic type Work_Type is private; with procedure Execute (Work : in out Work_Type); with procedure Error (Work : in out Work_Type; Err : in Ada.Exceptions.Exception_Occurrence) is null; Default_Queue_Size : Positive := 32; package Util.Executors is use Ada.Finalization; type Executor_Manager (Count : Positive) is limited new Limited_Controlled with private; type Executor_Manager_Access is access all Executor_Manager'Class; overriding procedure Initialize (Manager : in out Executor_Manager); -- Execute the work through the executor. procedure Execute (Manager : in out Executor_Manager; Work : in Work_Type); -- Start the executor tasks. procedure Start (Manager : in out Executor_Manager; Autostop : in Boolean := False); -- Stop the tasks and wait for their completion. procedure Stop (Manager : in out Executor_Manager); -- Set the work queue size. procedure Set_Queue_Size (Manager : in out Executor_Manager; Capacity : in Positive); -- Wait for the pending work to be executed by the executor tasks. procedure Wait (Manager : in out Executor_Manager); -- Get the number of elements in the queue. function Get_Count (Manager : in Executor_Manager) return Natural; -- Stop and release the executor. overriding procedure Finalize (Manager : in out Executor_Manager); private type Work_Info is record Work : Work_Type; Done : Boolean := False; end record; package Work_Queue is new Util.Concurrent.Fifos (Element_Type => Work_Info, Default_Size => Default_Queue_Size, Clear_On_Dequeue => True); task type Worker_Task is entry Start (Manager : in Executor_Manager_Access); end Worker_Task; type Worker_Task_Array is array (Positive range <>) of Worker_Task; type Executor_Manager (Count : Positive) is limited new Limited_Controlled with record Self : Executor_Manager_Access; Autostop : Boolean := False; Queue : Work_Queue.Fifo; Workers : Worker_Task_Array (1 .. Count); end record; end Util.Executors;
Add Get_Count and Wait operation on the executors
Add Get_Count and Wait operation on the executors
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c4e0857e71dd0a40fe56c57406f0d22bc49e8507
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; 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; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; H : Applications.Views.View_Handler; 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; Resolver : aliased Default_ELResolver; Conf : Applications.Config; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; begin H.Initialize (Conf); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); ELContext.Set_Resolver (Resolver'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", 8192); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response)); H.Close; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; 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 ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; H : Applications.Views.View_Handler; 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; Resolver : aliased Default_ELResolver; Conf : Applications.Config; Output : ASF.Streams.Print_Stream; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; begin H.Initialize (Conf); Context.Set_Response_Writer (Writer'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); ELContext.Set_Resolver (Resolver'Unchecked_Access); Writer.Initialize ("text/xml", "UTF-8", Output); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response)); H.Close; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Fix compilation
Fix compilation
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
3251e047d922a878d6fe4cf73d1a21f6a7762230
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014, 2015, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. -- ------------------------------ function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table is Length : Natural; begin if Max_Level > 0 and Max_Level < Frame.Depth then Length := Max_Level; else Length := Frame.Depth; end if; declare Current : Frame_Type := Frame; Pos : Natural := Length; Pc : Frame_Table (1 .. Length); begin while Current /= null and Pos /= 0 loop Pc (Pos) := Current.Pc; Pos := Pos - 1; Current := Current.Parent; end loop; return Pc; end; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Pc; Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame '(Parent => null, Depth => 0, Pc => 0, others => <>); end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Frame.Children := F.Next; Destroy (F); end loop; Free (Frame); end Destroy; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F.Children; Parent : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; begin while Pos <= Pc'Last loop Current_Depth := Current_Depth + 1; Child := new Frame '(Parent => Parent, Next => Child, Children => null, Used => 1, Depth => Current_Depth, Pc => Pc (Pos)); Pos := Pos + 1; Parent.Children := Child; Parent := Child; Child := null; end loop; Result := Parent; end Add_Frame; -- ------------------------------ -- 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 Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Parent : Frame_Type := Frame; Current : Frame_Type := Frame.Children; Pos : Positive := Pc'First; Addr : MAT.Types.Target_Addr; begin if Pc'Length = 0 then Result := Frame; Frame.Used := Frame.Used + 1; return; end if; if Current = null then Add_Frame (Frame, Pc, Result); return; end if; Addr := Pc (Pos); loop if Addr = Current.Pc then Current.Used := Current.Used + 1; Pos := Pos + 1; if Pos > Pc'Last then Result := Current; return; end if; if Current.Children = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Parent := Current; Current := Current.Children; Addr := Pc (Pos); elsif Current.Next = null then Add_Frame (Parent, Pc (Pos .. Pc'Last), Result); return; else Current := Current.Next; end if; end loop; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Pc = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ -- function Find (Frame : in Frame_Type; -- Pc : in Frame_Table) return Frame_Type is -- Child : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- begin -- while Pos <= Pc'Last loop -- Child := Find (Child, Pc (Pos)); -- Pos := Pos + 1; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop -- if Child.Calls (Lpos) /= Pc (Pos) then -- raise Not_Found; -- end if; -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end loop; -- return Child; -- end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- -- ------------------------------ -- procedure Find (Frame : in Frame_Type; -- Pc : in Frame_Table; -- Result : out Frame_Type; -- Last_Pc : out Natural) is -- Current : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- Lpos : Positive; -- begin -- Main_Search : -- while Pos <= Pc'Last loop -- declare -- Addr : constant MAT.Types.Target_Addr := Pc (Pos); -- Child : Frame_Type := Current.Children; -- begin -- -- Find the child which has the corresponding PC. -- loop -- exit Main_Search when Child = null; -- exit when Child.Pc = Addr; -- Child := Child.Next; -- end loop; -- -- Current := Child; -- Pos := Pos + 1; -- Lpos := 2; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop -- exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end; -- end loop Main_Search; -- Result := Current; -- if Pos > Pc'Last then -- Last_Pc := 0; -- else -- Last_Pc := Pos; -- end if; -- end Find; -- ------------------------------ -- Check whether the frame contains a call to the function described by the address range. -- ------------------------------ function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is Current : Frame_Type := Frame; begin while Current /= null loop if Current.Pc >= From and Current.Pc <= To then return True; end if; Current := Current.Parent; end loop; return False; end In_Function; -- ------------------------------ -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. -- ------------------------------ function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is begin return Frame /= null and then Frame.Pc >= From and then Frame.Pc <= To; end By_Function; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014, 2015, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. -- ------------------------------ function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table is Length : Natural; begin if Max_Level > 0 and Max_Level < Frame.Depth then Length := Max_Level; else Length := Frame.Depth; end if; declare Current : Frame_Type := Frame; Pos : Natural := Length; Pc : Frame_Table (1 .. Length); begin while Current /= null and Pos /= 0 loop Pc (Pos) := Current.Pc; Pos := Pos - 1; Current := Current.Parent; end loop; return Pc; end; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Pc; Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame '(Parent => null, Depth => 0, Pc => 0, others => <>); end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Frame.Children := F.Next; Destroy (F); end loop; Free (Frame); end Destroy; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F.Children; Parent : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; begin while Pos <= Pc'Last loop Current_Depth := Current_Depth + 1; Child := new Frame '(Parent => Parent, Next => Child, Children => null, Used => 1, Depth => Current_Depth, Pc => Pc (Pos)); Pos := Pos + 1; Parent.Children := Child; Parent := Child; Child := null; end loop; Result := Parent; end Add_Frame; -- ------------------------------ -- 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 Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Parent : Frame_Type := Frame; Current : Frame_Type := Frame.Children; Pos : Positive := Pc'First; Addr : MAT.Types.Target_Addr; begin if Pc'Length = 0 then Result := Frame; Frame.Used := Frame.Used + 1; return; end if; if Current = null then Frame.Used := Frame.Used + 1; Add_Frame (Frame, Pc, Result); return; end if; Addr := Pc (Pos); loop if Addr = Current.Pc then Parent.Used := Parent.Used + 1; Pos := Pos + 1; if Pos > Pc'Last then Current.Used := Current.Used + 1; Result := Current; return; end if; if Current.Children = null then Current.Used := Current.Used + 1; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Parent := Current; Current := Current.Children; Addr := Pc (Pos); elsif Current.Next = null then Parent.Used := Parent.Used + 1; Add_Frame (Parent, Pc (Pos .. Pc'Last), Result); return; else Current := Current.Next; end if; end loop; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Pc = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ -- function Find (Frame : in Frame_Type; -- Pc : in Frame_Table) return Frame_Type is -- Child : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- begin -- while Pos <= Pc'Last loop -- Child := Find (Child, Pc (Pos)); -- Pos := Pos + 1; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop -- if Child.Calls (Lpos) /= Pc (Pos) then -- raise Not_Found; -- end if; -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end loop; -- return Child; -- end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- -- ------------------------------ -- procedure Find (Frame : in Frame_Type; -- Pc : in Frame_Table; -- Result : out Frame_Type; -- Last_Pc : out Natural) is -- Current : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- Lpos : Positive; -- begin -- Main_Search : -- while Pos <= Pc'Last loop -- declare -- Addr : constant MAT.Types.Target_Addr := Pc (Pos); -- Child : Frame_Type := Current.Children; -- begin -- -- Find the child which has the corresponding PC. -- loop -- exit Main_Search when Child = null; -- exit when Child.Pc = Addr; -- Child := Child.Next; -- end loop; -- -- Current := Child; -- Pos := Pos + 1; -- Lpos := 2; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop -- exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end; -- end loop Main_Search; -- Result := Current; -- if Pos > Pc'Last then -- Last_Pc := 0; -- else -- Last_Pc := Pos; -- end if; -- end Find; -- ------------------------------ -- Check whether the frame contains a call to the function described by the address range. -- ------------------------------ function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is Current : Frame_Type := Frame; begin while Current /= null loop if Current.Pc >= From and Current.Pc <= To then return True; end if; Current := Current.Parent; end loop; return False; end In_Function; -- ------------------------------ -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. -- ------------------------------ function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is begin return Frame /= null and then Frame.Pc >= From and then Frame.Pc <= To; end By_Function; end MAT.Frames;
Fix the Used counter that was not incremented correctly
Fix the Used counter that was not incremented correctly
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ce158beeaa7a8233e73b7f787c50be6b18d48ff7
awa/src/awa-events-queues.ads
awa/src/awa-events-queues.ads
----------------------------------------------------------------------- -- awa-events-queues -- AWA Event Queues -- 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.Refs; with EL.Beans; with EL.Contexts; with AWA.Events.Models; package AWA.Events.Queues is type Queue_Ref is tagged private; -- Queue the event. procedure Enqueue (Into : in Queue_Ref; Event : in AWA.Events.Module_Event'Class); -- Dequeue an event and process it with the <b>Process</b> procedure. procedure Dequeue (From : in Queue_Ref; Process : access procedure (Event : in Module_Event'Class)); -- Returns true if the reference does not contain any element. function Is_Null (Queue : in Queue_Ref'Class) return Boolean; -- pragma Inline_Always (Is_Null); SCz 2012-03-17: disabled since gnat crashes. -- Returns the queue name. function Get_Name (Queue : in Queue_Ref'Class) return String; -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref; -- Create the event queue identified by the name <b>Name</b>. The queue factory -- identified by <b>Kind</b> is called to create the event queue instance. -- Returns a reference to the queue. function Create_Queue (Name : in String; Kind : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Ref; function Null_Queue return Queue_Ref; private type Queue is limited interface; type Queue_Access is access all Queue'Class; -- Get the queue name. function Get_Name (From : in Queue) return String is abstract; -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. function Get_Queue (From : in Queue) return AWA.Events.Models.Queue_Ref is abstract; -- Queue the event. procedure Enqueue (Into : in out Queue; Event : in AWA.Events.Module_Event'Class) is abstract; -- Dequeue an event and process it with the <b>Process</b> procedure. procedure Dequeue (From : in out Queue; Process : access procedure (Event : in Module_Event'Class)) is abstract; -- Release the queue storage. procedure Finalize (From : in out Queue) is null; type Queue_Info (Length : Natural) is new Util.Refs.Ref_Entity with record Queue : Queue_Access := null; Name : String (1 .. Length); end record; type Queue_Info_Access is access all Queue_Info; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out Queue_Info); package Queue_Refs is new Util.Refs.Indefinite_References (Queue_Info, Queue_Info_Access); type Queue_Ref is new Queue_Refs.Ref with null record; end AWA.Events.Queues;
----------------------------------------------------------------------- -- awa-events-queues -- AWA Event Queues -- Copyright (C) 2012, 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. ----------------------------------------------------------------------- private with Util.Refs; with EL.Beans; with EL.Contexts; with AWA.Events.Models; package AWA.Events.Queues is type Queue_Ref is tagged private; -- Queue the event. procedure Enqueue (Into : in Queue_Ref; Event : in AWA.Events.Module_Event'Class); -- Dequeue an event and process it with the <b>Process</b> procedure. procedure Dequeue (From : in Queue_Ref; Process : access procedure (Event : in Module_Event'Class)); -- Returns true if the queue is available. function Has_Queue (Queue : in Queue_Ref'Class) return Boolean; -- Returns the queue name. function Get_Name (Queue : in Queue_Ref'Class) return String; -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref; -- Create the event queue identified by the name <b>Name</b>. The queue factory -- identified by <b>Kind</b> is called to create the event queue instance. -- Returns a reference to the queue. function Create_Queue (Name : in String; Kind : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Ref; function Null_Queue return Queue_Ref; private type Queue is limited interface; type Queue_Access is access all Queue'Class; -- Get the queue name. function Get_Name (From : in Queue) return String is abstract; -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. function Get_Queue (From : in Queue) return AWA.Events.Models.Queue_Ref is abstract; -- Queue the event. procedure Enqueue (Into : in out Queue; Event : in AWA.Events.Module_Event'Class) is abstract; -- Dequeue an event and process it with the <b>Process</b> procedure. procedure Dequeue (From : in out Queue; Process : access procedure (Event : in Module_Event'Class)) is abstract; -- Release the queue storage. procedure Finalize (From : in out Queue) is null; type Queue_Info (Length : Natural) is new Util.Refs.Ref_Entity with record Queue : Queue_Access := null; Name : String (1 .. Length); end record; type Queue_Info_Access is access all Queue_Info; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out Queue_Info); package Queue_Refs is new Util.Refs.Indefinite_References (Queue_Info, Queue_Info_Access); subtype Queue_Info_Accessor is Queue_Refs.Element_Accessor; type Queue_Ref is new Queue_Refs.Ref with null record; end AWA.Events.Queues;
Change Is_Null into Has_Queue and define Queue_Info_Accessor
Change Is_Null into Has_Queue and define Queue_Info_Accessor
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c9419638ebc1c47d025fecc7fa32f122bcf56605
regtests/asf-servlets-tests.adb
regtests/asf-servlets-tests.adb
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); declare Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => "/home/test.jsf"); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Mapping /= null, "No mapping found"); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end; end Test_Request_Dispatcher; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access) is Map : constant Mapping_Access := Ctx.Find_Mapping (URI); begin if Map = null then T.Assert (Server = null, "No mapping returned for URI: " & URI); else T.Assert (Server /= null, "A mapping is returned for URI: " & URI); T.Assert (Map.Servlet = Server, "Invalid mapping returned for URI: " & URI); end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; Map : Mapping_Access; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); end loop; Util.Measures.Report (St, "Find 1000 mapping (extension)"); end; T.Assert (Map /= null, "No mapping for 'joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); end loop; Util.Measures.Report (St, "Find 1000 mapping (path)"); end; T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); end Add_Tests; end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. -- ------------------------------ procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String) is Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Mapping /= null, "No mapping found"); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path"); Assert_Equals (T, Path_Info, Req.Get_Path_Info, "The request path info is invalid"); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end Check_Request; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/home/test.jsf", "", "/home/test.jsf"); end Test_Request_Dispatcher; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Servlet_Path (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html"); end Test_Servlet_Path; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access) is Map : constant Mapping_Access := Ctx.Find_Mapping (URI); begin if Map = null then T.Assert (Server = null, "No mapping returned for URI: " & URI); else T.Assert (Server /= null, "A mapping is returned for URI: " & URI); T.Assert (Map.Servlet = Server, "Invalid mapping returned for URI: " & URI); end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; Map : Mapping_Access; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); end loop; Util.Measures.Report (St, "Find 1000 mapping (extension)"); end; T.Assert (Map /= null, "No mapping for 'joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); end loop; Util.Measures.Report (St, "Find 1000 mapping (path)"); end; T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path", Test_Servlet_Path'Access); end Add_Tests; end ASF.Servlets.Tests;
Add a unit test to check the request servlet path
Add a unit test to check the request servlet path
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
a507940ab8e57556a619c551a63a54da1898d0cd
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- 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 Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
Declare the Test_Starts_With procedure
Declare the Test_Starts_With procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5b5f4f674abee822e265e75ce8f5b2bff36d3783
awa/src/awa-applications-configs.adb
awa/src/awa-applications-configs.adb
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Permissions; with Security.Controllers.Roles; with AWA.Permissions.Configs; with AWA.Events.Configs; with AWA.Services.Contexts; package body AWA.Applications.Configs is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; Sec : constant Security.Permissions.Permission_Manager_Access := App.Get_Permission_Manager; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access, Context.all'Access); package Policy_Config is new Security.Permissions.Reader_Config (Reader, Sec); package Role_Config is new Security.Controllers.Roles.Reader_Config (Reader, Sec); package Entity_Config is new AWA.Permissions.Configs.Reader_Config (Reader, Sec); package Event_Config is new AWA.Events.Configs.Reader_Config (Reader => Reader, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); pragma Warnings (Off, Entity_Config); pragma Warnings (Off, Event_Config); end Reader_Config; -- ------------------------------ -- Read the application configuration file and configure the application -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Reader, App'Unchecked_Access, Context); pragma Warnings (Off, Config); begin -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Policies; with AWA.Events.Configs; with AWA.Services.Contexts; package body AWA.Applications.Configs is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Reader, App_Access, Context.all'Access); package Policy_Config is new Security.Policies.Reader_Config (Reader, Sec); package Event_Config is new AWA.Events.Configs.Reader_Config (Reader => Reader, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Event_Config); end Reader_Config; -- ------------------------------ -- Read the application configuration file and configure the application -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access) is Reader : Util.Serialize.IO.XML.Parser; Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Reader, App'Unchecked_Access, Context); pragma Warnings (Off, Config); begin -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.IO.Dump (Reader, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; end AWA.Applications.Configs;
Use the Security.Policies to configure the security permissions
Use the Security.Policies to configure the security permissions
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
392d2bf7d16c6f5d29e490013a59c5f46dd3434c
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; use type ADO.Drivers.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); -- T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); -- Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. -- T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Manager : Query_Manager; Config : ADO.Drivers.Connections.Configuration; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; use type ADO.Drivers.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Config : ADO.Drivers.Connections.Configuration; Manager : Query_Manager; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); -- T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); -- Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Manager, Config); -- T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, -- "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. -- T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Manager : Query_Manager; Config : ADO.Drivers.Connections.Configuration; begin ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; end ADO.Queries.Tests;
Simplify the unit test
Simplify the unit test
Ada
apache-2.0
stcarrez/ada-ado
9931ca6497f6b871900e9792eed6dbc006b336ea
regtests/ado-objects-tests.adb
regtests/ado-objects-tests.adb
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- 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.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'Access); 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'Access); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE'Access); 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.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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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'Access); 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'Access); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE'Access); 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;
Fix the unit test for the setting of a time stamp
Fix the unit test for the setting of a time stamp
Ada
apache-2.0
Letractively/ada-ado
44584bd42fceb2bce88145f9991b639e52128552
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 19, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 21, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
Update the schema test after introduction of new test tables
Update the schema test after introduction of new test tables
Ada
apache-2.0
stcarrez/ada-ado
5a7d0221b5f978cc5ca92e90304c04ae5846910d
matp/src/elf.ads
matp/src/elf.ads
----------------------------------------------------------------------- -- elf -- ELF information -- 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 Interfaces; package ELF is subtype Elf32_Word is Interfaces.Unsigned_32; subtype Elf64_Word is Interfaces.Unsigned_64; -- Legal values for the ELF header p_type (segment type). PT_NULL : constant Elf32_Word := 0; -- Program header table entry unused. PT_LOAD : constant Elf32_Word := 1; -- Loadable program segment PT_DYNAMIC : constant Elf32_Word := 2; -- Dynamic linking information PT_INTERP : constant Elf32_Word := 3; -- Program interpreter PT_NOTE : constant Elf32_Word := 4; -- Auxiliary information PT_SHLIB : constant Elf32_Word := 5; -- Reserved PT_PHDR : constant Elf32_Word := 6; -- Entry for header table itself PT_TLS : constant Elf32_Word := 7; -- Thread-local storage segment PT_NUM : constant Elf32_Word := 8; -- Number of defined types PT_LOOS : constant Elf32_Word := 16#60000000#; -- Start of OS-specific PT_GNU_EH_FRAME : constant Elf32_Word := 16#6474e550#; -- GCC .eh_frame_hdr segment PT_GNU_STACK : constant Elf32_Word := 16#6474e551#; -- Indicates stack executability PT_GNU_RELRO : constant Elf32_Word := 16#6474e552#; -- Read-only after relocation PT_LOSUNW : constant Elf32_Word := 16#6ffffffa#; PT_SUNWBSS : constant Elf32_Word := 16#6ffffffa#; -- Sun Specific segment PT_SUNWSTACK : constant Elf32_Word := 16#6ffffffb#; -- Stack segment PT_HISUNW : constant Elf32_Word := 16#6fffffff#; PT_HIOS : constant Elf32_Word := 16#6fffffff#; -- End of OS-specific PT_LOPROC : constant Elf32_Word := 16#70000000#; -- Start of processor-specific PT_HIPROC : constant Elf32_Word := 16#7fffffff#; -- End of processor-specific -- Legal values for ELF header p_flags (segment flags). PF_X : constant Elf32_Word := 1; -- Segment is executable. PF_W : constant Elf32_Word := 2; -- Segment is writable. PF_R : constant Elf32_Word := 4; -- Segment is readable. end ELF;
----------------------------------------------------------------------- -- elf -- ELF information -- 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 Interfaces; package ELF is pragma Preelaborate; subtype Elf32_Word is Interfaces.Unsigned_32; subtype Elf64_Word is Interfaces.Unsigned_64; -- Legal values for the ELF header p_type (segment type). PT_NULL : constant Elf32_Word := 0; -- Program header table entry unused. PT_LOAD : constant Elf32_Word := 1; -- Loadable program segment PT_DYNAMIC : constant Elf32_Word := 2; -- Dynamic linking information PT_INTERP : constant Elf32_Word := 3; -- Program interpreter PT_NOTE : constant Elf32_Word := 4; -- Auxiliary information PT_SHLIB : constant Elf32_Word := 5; -- Reserved PT_PHDR : constant Elf32_Word := 6; -- Entry for header table itself PT_TLS : constant Elf32_Word := 7; -- Thread-local storage segment PT_NUM : constant Elf32_Word := 8; -- Number of defined types PT_LOOS : constant Elf32_Word := 16#60000000#; -- Start of OS-specific PT_GNU_EH_FRAME : constant Elf32_Word := 16#6474e550#; -- GCC .eh_frame_hdr segment PT_GNU_STACK : constant Elf32_Word := 16#6474e551#; -- Indicates stack executability PT_GNU_RELRO : constant Elf32_Word := 16#6474e552#; -- Read-only after relocation PT_LOSUNW : constant Elf32_Word := 16#6ffffffa#; PT_SUNWBSS : constant Elf32_Word := 16#6ffffffa#; -- Sun Specific segment PT_SUNWSTACK : constant Elf32_Word := 16#6ffffffb#; -- Stack segment PT_HISUNW : constant Elf32_Word := 16#6fffffff#; PT_HIOS : constant Elf32_Word := 16#6fffffff#; -- End of OS-specific PT_LOPROC : constant Elf32_Word := 16#70000000#; -- Start of processor-specific PT_HIPROC : constant Elf32_Word := 16#7fffffff#; -- End of processor-specific -- Legal values for ELF header p_flags (segment flags). PF_X : constant Elf32_Word := 1; -- Segment is executable. PF_W : constant Elf32_Word := 2; -- Segment is writable. PF_R : constant Elf32_Word := 4; -- Segment is readable. end ELF;
Add pragma Preelaborate
Add pragma Preelaborate
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4a6243faa78eb8603cf6406716c8acb0f5409ae5
src/asf-servlets-rest.adb
src/asf-servlets-rest.adb
----------------------------------------------------------------------- -- asf-servlets-rest -- REST servlet -- 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 ASF.Applications; with ASF.Streams.JSON; with Util.Streams.Texts; with Util.Serialize.IO.JSON; package body ASF.Servlets.Rest is -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Rest_Servlet; Context : in Servlet_Registry'Class) is pragma Unreferenced (Context); Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context; begin if Ctx.all in ASF.Applications.Main.Application'Class then Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access; end if; end Initialize; -- ------------------------------ -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. -- ------------------------------ overriding procedure Service (Server : in Rest_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is Method : constant String := Request.Get_Method; begin if Method = "GET" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response); elsif Method = "POST" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "PUT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response); elsif Method = "DELETE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response); elsif Method = "HEAD" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "OPTIONS" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response); elsif Method = "TRACE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response); elsif Method = "CONNECT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response); else Response.Send_Error (Responses.SC_NOT_IMPLEMENTED); end if; end Service; procedure Dispatch (Server : in Rest_Servlet; Method : in ASF.Rest.Method_Type; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); use type ASF.Routes.Route_Type_Access; use type ASF.Routes.Servlets.Rest.API_Route_Type; use type ASF.Rest.Descriptor_Access; Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route; begin if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type := ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access; Desc : constant ASF.Rest.Descriptor_Access := Api.Descriptors (Method); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Stream : ASF.Streams.JSON.Print_Stream; begin if Desc = null then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; -- if not App.Has_Permission (Desc.Permission) then -- Response.Set_Status (ASF.Responses.SC_FORBIDDEN); -- return; -- end if; ASF.Streams.JSON.Initialize (Stream, Output); Api.Descriptors (Method).Dispatch (Request, Response, Stream); end; end Dispatch; function Create_Route (Registry : in ASF.Servlets.Servlet_Registry; Name : in String) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name); Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if not Servlet_Maps.Has_Element (Pos) then -- Log.Error ("No servlet {0}", Name); raise Servlet_Error with "No servlet " & Name; end if; Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet_Maps.Element (Pos); return Result; end Create_Route; -- Create a route for the REST API. function Create_Route (Servlet : in ASF.Servlets.Servlet_Access) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet; return Result; end Create_Route; end ASF.Servlets.Rest;
----------------------------------------------------------------------- -- asf-servlets-rest -- REST servlet -- 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 ASF.Applications; with ASF.Streams.JSON; package body ASF.Servlets.Rest is -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Rest_Servlet; Context : in Servlet_Registry'Class) is pragma Unreferenced (Context); Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context; begin if Ctx.all in ASF.Applications.Main.Application'Class then Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access; end if; end Initialize; -- ------------------------------ -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. -- ------------------------------ overriding procedure Service (Server : in Rest_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is Method : constant String := Request.Get_Method; begin if Method = "GET" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response); elsif Method = "POST" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "PUT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response); elsif Method = "DELETE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response); elsif Method = "HEAD" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "OPTIONS" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response); elsif Method = "TRACE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response); elsif Method = "CONNECT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response); else Response.Send_Error (Responses.SC_NOT_IMPLEMENTED); end if; end Service; procedure Dispatch (Server : in Rest_Servlet; Method : in ASF.Rest.Method_Type; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); use type ASF.Routes.Route_Type_Access; use type ASF.Routes.Servlets.Rest.API_Route_Type; use type ASF.Rest.Descriptor_Access; Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route; begin if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type := ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access; Desc : constant ASF.Rest.Descriptor_Access := Api.Descriptors (Method); Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; Stream : ASF.Streams.JSON.Print_Stream; begin if Desc = null then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; -- if not App.Has_Permission (Desc.Permission) then -- Response.Set_Status (ASF.Responses.SC_FORBIDDEN); -- return; -- end if; ASF.Streams.JSON.Initialize (Stream, Output); Api.Descriptors (Method).Dispatch (Request, Response, Stream); end; end Dispatch; function Create_Route (Registry : in ASF.Servlets.Servlet_Registry; Name : in String) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name); Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if not Servlet_Maps.Has_Element (Pos) then -- Log.Error ("No servlet {0}", Name); raise Servlet_Error with "No servlet " & Name; end if; Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet_Maps.Element (Pos); return Result; end Create_Route; -- Create a route for the REST API. function Create_Route (Servlet : in ASF.Servlets.Servlet_Access) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet; return Result; end Create_Route; end ASF.Servlets.Rest;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e8ab7c3ed2a5a47add417e5aa7e6a7f750b6928e
regtests/util-files-tests.adb
regtests/util-files-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; Last := To_Unbounded_String (Dir); end if; end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/os-none", Compose_Path ("src;regtests", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Test_Caller; package body Util.Files.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Files.Read_File", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)", Test_Read_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Write_File", Test_Write_File'Access); Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path", Test_Iterate_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path", Test_Find_File_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Compose_Path", Test_Compose_Path'Access); Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path", Test_Get_Relative_Path'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result); T.Assert (Index (Result, "Util.Files.Tests") > 0, "Content returned by Read_File is not correct"); T.Assert (Index (Result, "end Util.Files.Tests;") > 0, "Content returned by Read_File is not correct"); end Test_Read_File; procedure Test_Read_File_Missing (T : in out Test) is Result : Unbounded_String; pragma Unreferenced (Result); begin Read_File (Path => "regtests/files-test--util.adb", Into => Result); T.Assert (False, "No exception raised"); exception when others => null; end Test_Read_File_Missing; procedure Test_Read_File_Truncate (T : in out Test) is Result : Unbounded_String; begin Read_File (Path => "regtests/util-files-tests.adb", Into => Result, Max_Size => 50); Assert_Equals (T, Length (Result), 50, "Read_File did not truncate correctly"); T.Assert (Index (Result, "Apache License") > 0, "Content returned by Read_File is not correct"); end Test_Read_File_Truncate; -- ------------------------------ -- Check writing a file -- ------------------------------ procedure Test_Write_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt"); Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF; Result : Unbounded_String; begin Write_File (Path => Path, Content => Content); Read_File (Path => Path, Into => Result); Assert_Equals (T, To_String (Result), Content, "Invalid content written or read"); end Test_Write_File; -- ------------------------------ -- Check Find_File_Path -- ------------------------------ procedure Test_Find_File_Path (T : in out Test) is Dir : constant String := Util.Tests.Get_Path ("regtests"); Paths : constant String := ".;" & Dir; begin declare P : constant String := Util.Files.Find_File_Path ("test.properties", Paths); begin Assert_Equals (T, Dir & "/test.properties", P, "Invalid path returned"); end; Assert_Equals (T, "blablabla.properties", Util.Files.Find_File_Path ("blablabla.properties", Paths)); end Test_Find_File_Path; -- ------------------------------ -- Check Iterate_Path -- ------------------------------ procedure Test_Iterate_Path (T : in out Test) is procedure Check_Path (Dir : in String; Done : out Boolean); Last : Unbounded_String; procedure Check_Path (Dir : in String; Done : out Boolean) is begin if Dir = "a" or Dir = "bc" or Dir = "de" then Done := False; else Done := True; end if; Last := To_Unbounded_String (Dir); end Check_Path; begin Iterate_Path ("a;bc;de;f", Check_Path'Access); Assert_Equals (T, "f", Last, "Invalid last path"); Iterate_Path ("de;bc;de;b", Check_Path'Access); Assert_Equals (T, "b", Last, "Invalid last path"); Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward); Assert_Equals (T, "de", Last, "Invalid last path"); end Test_Iterate_Path; -- ------------------------------ -- Test the Compose_Path operation -- ------------------------------ procedure Test_Compose_Path (T : in out Test) is begin Assert_Equals (T, "src/os-none", Compose_Path ("src;regtests", "os-none"), "Invalid path composition"); Assert_Equals (T, "regtests/bundles", Compose_Path ("src;regtests", "bundles"), "Invalid path composition"); if Ada.Directories.Exists ("/usr/bin") then Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin", Compose_Path ("/usr;/usr/local;/usr", "bin"), "Invalid path composition"); end if; end Test_Compose_Path; -- ------------------------------ -- Test the Get_Relative_Path operation. -- ------------------------------ procedure Test_Get_Relative_Path (T : in out Test) is begin Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util", Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"), "Invalid relative path"); Assert_Equals (T, "../util/b", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"), "Invalid relative path"); Assert_Equals (T, "../as", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"), "Invalid relative path"); Assert_Equals (T, "../../", Get_Relative_Path ("/home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "/usr/share/admin", Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"), "Invalid absolute path"); Assert_Equals (T, "/home/john", Get_Relative_Path ("home/john/src/asf", "/home/john"), "Invalid relative path"); Assert_Equals (T, "e", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"), "Invalid relative path"); Assert_Equals (T, ".", Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"), "Invalid relative path"); end Test_Get_Relative_Path; end Util.Files.Tests;
Add test to check iterating over the search paths in reverse order
Add test to check iterating over the search paths in reverse order
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ae585c99a22182c824d5862b8905094a4fb64804
src/util-serialize-contexts.adb
src/util-serialize-contexts.adb
----------------------------------------------------------------------- -- util-serialize-contexts -- Contexts for serialization framework -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Concurrent.Locks; package body Util.Serialize.Contexts is procedure Free is new Ada.Unchecked_Deallocation (Data'Class, Data_Access); -- ------------------------------ -- Context data key -- ------------------------------ Lock : Util.Concurrent.Locks.RW_Lock; Next_Key : Data_Key := 1; -- ------------------------------ -- Allocate a unique data key for a mapper. -- ------------------------------ procedure Allocate (Key : out Data_Key) is begin Lock.Write; Key := Next_Key; Next_Key := Next_Key + 1; Lock.Release_Write; end Allocate; function Hash (Key : in Data_Key) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Reader context -- ------------------------------ -- ------------------------------ -- Get the data object associated with the given key. -- Raises No_Data exception if there is no data object. -- ------------------------------ function Get_Data (Ctx : in Context; Key : in Data_Key) return Data_Access is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then return Data_Map.Element (Pos); else raise No_Data; end if; end Get_Data; -- ------------------------------ -- Set the data object associated with the given key. -- ------------------------------ procedure Set_Data (Ctx : in out Context; Key : in Data_Key; Content : in Data_Access) is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then declare Old : Data_Access := Data_Map.Element (Pos); begin if Old = Content then return; end if; Free (Old); end; Ctx.Data.Replace_Element (Position => Pos, New_Item => Content); else Ctx.Data.Insert (Key => Key, New_Item => Content); end if; end Set_Data; -- ------------------------------ -- Free the context data. -- ------------------------------ overriding procedure Finalize (Ctx : in out Context) is Pos : Data_Map.Cursor; Content : Data_Access; begin loop Pos := Ctx.Data.First; exit when not Data_Map.Has_Element (Pos); Content := Data_Map.Element (Pos); Free (Content); Ctx.Data.Delete (Pos); end loop; end Finalize; end Util.Serialize.Contexts;
----------------------------------------------------------------------- -- util-serialize-contexts -- Contexts for serialization framework -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Concurrent.Counters; package body Util.Serialize.Contexts is procedure Free is new Ada.Unchecked_Deallocation (Data'Class, Data_Access); -- ------------------------------ -- Context data key -- ------------------------------ Next_Key : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; -- ------------------------------ -- Allocate a unique data key for a mapper. -- ------------------------------ procedure Allocate (Key : out Data_Key) is Val : Integer; begin Util.Concurrent.Counters.Increment (Next_Key, Val); Key := Data_Key (Val); end Allocate; function Hash (Key : in Data_Key) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Reader context -- ------------------------------ -- ------------------------------ -- Get the data object associated with the given key. -- Raises No_Data exception if there is no data object. -- ------------------------------ function Get_Data (Ctx : in Context; Key : in Data_Key) return Data_Access is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then return Data_Map.Element (Pos); else raise No_Data; end if; end Get_Data; -- ------------------------------ -- Set the data object associated with the given key. -- ------------------------------ procedure Set_Data (Ctx : in out Context; Key : in Data_Key; Content : in Data_Access) is Pos : constant Data_Map.Cursor := Ctx.Data.Find (Key); begin if Data_Map.Has_Element (Pos) then declare Old : Data_Access := Data_Map.Element (Pos); begin if Old = Content then return; end if; Free (Old); end; Ctx.Data.Replace_Element (Position => Pos, New_Item => Content); else Ctx.Data.Insert (Key => Key, New_Item => Content); end if; end Set_Data; -- ------------------------------ -- Free the context data. -- ------------------------------ overriding procedure Finalize (Ctx : in out Context) is Pos : Data_Map.Cursor; Content : Data_Access; begin loop Pos := Ctx.Data.First; exit when not Data_Map.Has_Element (Pos); Content := Data_Map.Element (Pos); Free (Content); Ctx.Data.Delete (Pos); end loop; end Finalize; end Util.Serialize.Contexts;
Use the atomic increment and get counter operation instead of a RW lock
Use the atomic increment and get counter operation instead of a RW lock
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f16d329b5b97cbf75f50dfc31b5bb0dbe9669119
src/wiki-plugins-conditions.adb
src/wiki-plugins-conditions.adb
----------------------------------------------------------------------- -- wiki-plugins-conditions -- Condition Plugin -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Plugins.Conditions is -- ------------------------------ -- Append the attribute name/value to the condition plugin parameter list. -- ------------------------------ procedure Append (Plugin : in out Condition_Plugin; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Attributes.Append (Plugin.Params, Name, Value); end Append; -- ------------------------------ -- Evaluate the condition and return it as a boolean status. -- ------------------------------ function Evaluate (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Boolean is procedure Check (Name : in String; Value : in Wiki.Strings.WString); Result : Boolean := False; Index : Natural := 0; procedure Check (Name : in String; Value : in Wiki.Strings.WString) is pragma Unreferenced (Name); Pos : Wiki.Attributes.Cursor; begin Index := Index + 1; if Index > 1 and not Result then Pos := Attributes.Find (Plugin.Params, Wiki.Strings.To_String (Value)); Result := Attributes.Has_Element (Pos); end if; end Check; begin Attributes.Iterate (Params, Check'Access); return Result; end Evaluate; -- ------------------------------ -- Get the type of condition (IF, ELSE, ELSIF, END) represented by the plugin. -- ------------------------------ function Get_Condition_Kind (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Condition_Type is pragma Unreferenced (Plugin); Name : constant Strings.WString := Attributes.Get_Attribute (Params, "name"); begin if Name = "if" then return CONDITION_IF; elsif Name = "else" then return CONDITION_ELSE; elsif Name = "elsif" then return CONDITION_ELSIF; elsif Name = "end" then return CONDITION_END; else return CONDITION_IF; end if; end Get_Condition_Kind; -- ------------------------------ -- Evaluate the condition described by the parameters and hide or show the wiki -- content. -- ------------------------------ overriding procedure Expand (Plugin : in out Condition_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is pragma Unreferenced (Document); Kind : constant Condition_Type := Condition_Plugin'Class (Plugin).Get_Condition_Kind (Params); begin case Kind is when CONDITION_IF => Plugin.Depth := Plugin.Depth + 1; Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSIF => Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSE => Plugin.Values (Plugin.Depth) := not Plugin.Values (Plugin.Depth); when CONDITION_END => Plugin.Depth := Plugin.Depth - 1; end case; Context.Previous.Is_Hidden := Plugin.Values (Plugin.Depth); end Expand; end Wiki.Plugins.Conditions;
----------------------------------------------------------------------- -- wiki-plugins-conditions -- Condition Plugin -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Plugins.Conditions is -- ------------------------------ -- Append the attribute name/value to the condition plugin parameter list. -- ------------------------------ procedure Append (Plugin : in out Condition_Plugin; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Attributes.Append (Plugin.Params, Name, Value); end Append; -- ------------------------------ -- Evaluate the condition and return it as a boolean status. -- ------------------------------ function Evaluate (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Boolean is procedure Check (Name : in String; Value : in Wiki.Strings.WString); Result : Boolean := False; Index : Natural := 0; procedure Check (Name : in String; Value : in Wiki.Strings.WString) is pragma Unreferenced (Name); Pos : Wiki.Attributes.Cursor; begin Index := Index + 1; if Index > 1 and not Result then Pos := Attributes.Find (Plugin.Params, Wiki.Strings.To_String (Value)); Result := Attributes.Has_Element (Pos); end if; end Check; begin Attributes.Iterate (Params, Check'Access); return Result; end Evaluate; -- ------------------------------ -- Get the type of condition (IF, ELSE, ELSIF, END) represented by the plugin. -- ------------------------------ function Get_Condition_Kind (Plugin : in Condition_Plugin; Params : in Wiki.Attributes.Attribute_List) return Condition_Type is pragma Unreferenced (Plugin); Name : constant Strings.WString := Attributes.Get_Attribute (Params, "name"); begin if Name = "if" then return CONDITION_IF; elsif Name = "else" then return CONDITION_ELSE; elsif Name = "elsif" then return CONDITION_ELSIF; elsif Name = "end" then return CONDITION_END; else return CONDITION_IF; end if; end Get_Condition_Kind; -- ------------------------------ -- Evaluate the condition described by the parameters and hide or show the wiki -- content. -- ------------------------------ overriding procedure Expand (Plugin : in out Condition_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Document); Kind : constant Condition_Type := Condition_Plugin'Class (Plugin).Get_Condition_Kind (Params); begin case Kind is when CONDITION_IF => Plugin.Depth := Plugin.Depth + 1; Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSIF => Plugin.Values (Plugin.Depth) := not Condition_Plugin'Class (Plugin).Evaluate (Params); when CONDITION_ELSE => Plugin.Values (Plugin.Depth) := not Plugin.Values (Plugin.Depth); when CONDITION_END => Plugin.Depth := Plugin.Depth - 1; end case; Context.Previous.Is_Hidden := Plugin.Values (Plugin.Depth); end Expand; end Wiki.Plugins.Conditions;
Change the Context parameter to 'in out' because we may need to access the filters
Change the Context parameter to 'in out' because we may need to access the filters
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cfa69d0597972668282df8b3c2df56185c70ad5e
src/gen-commands-templates.ads
src/gen-commands-templates.ads
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Strings.Sets; with Util.Strings.Vectors; package Gen.Commands.Templates is -- ------------------------------ -- Template Generic Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with private; type Command_Access is access all Command'Class; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Read the template commands defined in dynamo configuration directory. procedure Read_Commands (Generator : in out Gen.Generator.Handler); private type Param is record Name : Ada.Strings.Unbounded.Unbounded_String; Argument : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Is_Optional : Boolean := False; end record; package Param_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Param); type Patch is record Template : Ada.Strings.Unbounded.Unbounded_String; After : Util.Strings.Vectors.Vector; Missing : Util.Strings.Vectors.Vector; Before : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Optional : Boolean := False; end record; package Patch_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Patch); type Command is new Gen.Commands.Command with record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; Help_Msg : Ada.Strings.Unbounded.Unbounded_String; Base_Dir : Ada.Strings.Unbounded.Unbounded_String; Templates : Util.Strings.Sets.Set; Patches : Patch_Vectors.Vector; Params : Param_Vectors.Vector; end record; end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Strings.Sets; with Util.Strings.Vectors; package Gen.Commands.Templates is -- ------------------------------ -- Template Generic Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with private; type Command_Access is access all Command'Class; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler); -- Read the template commands defined in dynamo configuration directory. procedure Read_Commands (Generator : in out Gen.Generator.Handler); private type Param is record Name : Ada.Strings.Unbounded.Unbounded_String; Argument : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Is_Optional : Boolean := False; end record; package Param_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Param); type Patch is record Template : Ada.Strings.Unbounded.Unbounded_String; After : Util.Strings.Vectors.Vector; Missing : Util.Strings.Vectors.Vector; Before : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Optional : Boolean := False; end record; package Patch_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Patch); type Command is new Gen.Commands.Command with record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; Help_Msg : Ada.Strings.Unbounded.Unbounded_String; Base_Dir : Ada.Strings.Unbounded.Unbounded_String; Templates : Util.Strings.Sets.Set; Patches : Patch_Vectors.Vector; Params : Param_Vectors.Vector; end record; end Gen.Commands.Templates;
Update to use an in out parameter for Help procedure
Update to use an in out parameter for Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
7c5e8e9cfc7b37cac263d5d4f7516f538838bb79
matp/src/frames/mat-frames.ads
matp/src/frames/mat-frames.ads
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- 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.Types; -- with MAT.Events; package MAT.Frames is Not_Found : exception; type Frame_Type is private; type Frame_Table is array (Natural range <>) of MAT.Types.Target_Addr; -- subtype Frame_Table is MAT.Events.Frame_Table; -- Return the parent frame. function Parent (Frame : in Frame_Type) return Frame_Type; -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table; -- Returns all the direct calls made by the current frame. function Calls (Frame : in Frame_Type) return Frame_Table; -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural; -- Returns the current stack depth (# of calls from the root -- to reach the frame). function Current_Depth (Frame : in Frame_Type) return Natural; -- Create a root for stack frame representation. function Create_Root return Frame_Type; -- Destroy the frame tree recursively. procedure Destroy (Frame : in out Frame_Type); -- Release the frame when its reference is no longer necessary. procedure Release (Frame : in Frame_Type); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type; function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural); -- Check whether the frame contains a call to the function described by the address range. function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean; -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean; private Frame_Group_Size : constant Natural := 4; subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size; subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last); type Frame; type Frame_Type is access all Frame; type Frame is record Parent : Frame_Type := null; Next : Frame_Type := null; Children : Frame_Type := null; Used : Natural := 0; Depth : Natural := 0; Calls : Mini_Frame_Table; Local_Depth : Local_Depth_Type := 0; end record; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- 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.Types; package MAT.Frames is Not_Found : exception; type Frame_Type is private; type Frame_Table is array (Natural range <>) of MAT.Types.Target_Addr; -- Return the parent frame. function Parent (Frame : in Frame_Type) return Frame_Type; -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table; -- Returns all the direct calls made by the current frame. function Calls (Frame : in Frame_Type) return Frame_Table; -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural; -- Returns the current stack depth (# of calls from the root -- to reach the frame). function Current_Depth (Frame : in Frame_Type) return Natural; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type; -- Check whether the frame contains a call to the function described by the address range. function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean; -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean; procedure Verify_Frames; private type Frame; type Frame_Type is access all Frame; -- The frame information is readonly and we can safely use the By_Function, In_Function -- and Backtrace without protection. Insertion and creation of stack frame must be -- protected through a protected type managed by Target_Frames. All the frame instances -- are released when the Target_Frames protected type is released. type Frame (Parent : Frame_Type; Depth : Natural; Pc : MAT.Types.Target_Addr) is limited record Next : Frame_Type := null; Children : Frame_Type := null; Used : Natural := 0; end record; -- Create a root for stack frame representation. function Create_Root return Frame_Type; -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- Destroy the frame tree recursively. procedure Destroy (Frame : in out Frame_Type); end MAT.Frames;
Refactor and simplify the stack frame management and representation - Make the Create_Root, Insert, Destroy private operations - Change the Frame record to a limited record with readonly members and keep only one PC address per Frame record instance
Refactor and simplify the stack frame management and representation - Make the Create_Root, Insert, Destroy private operations - Change the Frame record to a limited record with readonly members and keep only one PC address per Frame record instance
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6ce209103f959fd85778593bf3df8497209b19d2
src/asf-applications-main.ads
src/asf-applications-main.ads
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Permissions; use Security; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the permission manager. The permission manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Permissions.Permission_Manager</b> object. function Create_Permission_Manager (App : in Application_Factory) return Security.Permissions.Permission_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Permission_Manager (App : in Application) return Security.Permissions.Permission_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. 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. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access := null; -- The permission manager. Permissions : Security.Permissions.Permission_Manager_Access := null; end record; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. 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. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access := null; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access := null; end record; end ASF.Applications.Main;
Rename Permission_Manager into Security_Manager
Rename Permission_Manager into Security_Manager
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
2b027b96e270c5722b2e3e6654264664dea88bcd
regtests/util-serialize-io-form-tests.adb
regtests/util-serialize-io-form-tests.adb
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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 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.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is 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); -- T.Fail ("No exception for " & Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is 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); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); 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.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, 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 => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
----------------------------------------------------------------------- -- util-serialize-io-form-tests -- Unit tests for form parser -- 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 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.Form.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various form parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is 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); T.Fail ("No exception for " & Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("bad"); Check_Parse_Error ("bad=%rw%ad"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSformON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is 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); T.Fail ("Parse error for: " & Content); end Check_Parse; begin Check_Parse ("name=value"); Check_Parse ("name=value&param=value"); Check_Parse ("name+name=value+value"); Check_Parse ("name%20%30=value%23%ce"); 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.Form.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, 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 => "Form output serialization"); end Test_Output; -- ------------------------------ -- Test reading a form content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array"); Value := Util.Beans.Objects.Get_Value (Root, "home"); Util.Tests.Assert_Equals (T, "Cosby", Util.Beans.Objects.To_String (Value), "Invalid first parameter"); Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor"); Util.Tests.Assert_Equals (T, "flies", Util.Beans.Objects.To_String (Value), "Invalid second parameter"); end Test_Read; end Util.Serialize.IO.Form.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
70224bf8d2a3010def96dc7a2601b77eb3814c0e
src/gen-commands-database.adb
src/gen-commands-database.adb
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- 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 GNAT.Command_Line; with GNAT.Expect; with GNAT.OS_Lib; with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with ADO.Drivers.Connections; with ADO.Sessions.Factory; with ADO.Statements; with ADO.Queries; with ADO.Parameters; with System; with Gen.Database.Model; package body Gen.Commands.Database is use GNAT.Command_Line; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database"); -- Check if the database with the given name exists. function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Check if the database with the given name has some tables. function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Expect filter to print the command output/error procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address); -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String); -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler); -- Create the database identified by the given name. procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String); -- Create the user and grant him access to the database. procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String); -- ------------------------------ -- Check if the database with the given name exists. -- ------------------------------ function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Database_List); Stmt := DB.Create_Statement (Query); Stmt.Execute; while Stmt.Has_Elements loop declare D : constant String := Stmt.Get_String (0); begin if Name = D then return True; end if; end; Stmt.Next; end loop; return False; end Has_Database; -- ------------------------------ -- Check if the database with the given name has some tables. -- ------------------------------ function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Table_List); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; return Stmt.Has_Elements; end Has_Tables; -- ------------------------------ -- Create the database identified by the given name. -- ------------------------------ procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Creating database '{0}'", Name); Query.Set_Query (Gen.Database.Model.Query_Create_Database); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; end Create_Database; -- ------------------------------ -- Create the user and grant him access to the database. -- ------------------------------ procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name); if Password'Length > 0 then Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password); else Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password); end if; Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Bind_Param ("user", ADO.Parameters.Token (User)); if Password'Length > 0 then Stmt.Bind_Param ("password", Password); end if; Stmt.Execute; Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges); Stmt := DB.Create_Statement (Query); Stmt.Execute; end Create_User_Grant; -- ------------------------------ -- Expect filter to print the command output/error -- ------------------------------ procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address) is pragma Unreferenced (Descriptor, Closure); begin Log.Error ("{0}", Data); end Command_Output; -- ------------------------------ -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. -- ------------------------------ procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String) is Proc : GNAT.Expect.Process_Descriptor; Status : Integer; Func : constant GNAT.Expect.Filter_Function := Command_Output'Access; Result : GNAT.Expect.Expect_Match; Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => Input, Into => Content); GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc, Command => Name, Args => Args, Buffer_Size => 4096, Err_To_Out => True); GNAT.Expect.Add_Filter (Descriptor => Proc, Filter => Func, Filter_On => GNAT.Expect.Output); GNAT.Expect.Send (Descriptor => Proc, Str => Ada.Strings.Unbounded.To_String (Content), Add_LF => False, Empty_Buffer => False); GNAT.Expect.Expect (Proc, Result, ".*"); GNAT.Expect.Close (Descriptor => Proc, Status => Status); if Status = 0 then Log.Info ("Database schema created successfully."); else Log.Error ("Error while creating the database schema."); end if; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read {0}", Input); end Execute_Command; -- ------------------------------ -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. -- ------------------------------ procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler) is Database : constant String := Config.Get_Database; Username : constant String := Config.Get_Property ("user"); Password : constant String := Config.Get_Property ("password"); Dir : constant String := Util.Files.Compose (Model, "mysql"); File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql"); begin Log.Info ("Creating database tables using schema '{0}'", File); if not Ada.Directories.Exists (File) then Generator.Error ("SQL file '{0}' does not exist.", File); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Password'Length > 0 then declare Args : GNAT.OS_Lib.Argument_List (1 .. 3); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '("--password=" & Password); Args (3) := new String '(Database); Execute_Command ("mysql", Args, File); end; else declare Args : GNAT.OS_Lib.Argument_List (1 .. 2); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '(Database); Execute_Command ("mysql", Args, File); end; end if; end Create_Mysql_Tables; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String) is Factory : ADO.Sessions.Factory.Session_Factory; Config : ADO.Drivers.Connections.Configuration; Root_Connection : Unbounded_String; Pos : Natural; begin Config.Set_Connection (Database); if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; -- Build a connection string to create the database. Pos := Util.Strings.Index (Database, ':'); Append (Root_Connection, Database (Database'First .. Pos)); Append (Root_Connection, "//"); Append (Root_Connection, Config.Get_Server); if Config.Get_Port > 0 then Append (Root_Connection, ':'); Append (Root_Connection, Util.Strings.Image (Config.Get_Port)); end if; Append (Root_Connection, "/?user="); Append (Root_Connection, Username); if Password'Length > 0 then Append (Root_Connection, "&password="); Append (Root_Connection, Password); end if; Log.Info ("Connecting to {0}", Root_Connection); -- Initialize the session factory to connect to the -- database defined by root connection (which should allow the database creation). Factory.Create (To_String (Root_Connection)); declare Name : constant String := Generator.Get_Project_Name; DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin -- Create the database only if it does not already exists. if not Has_Database (DB, Config.Get_Database) then Create_Database (DB, Config.Get_Database); end if; -- If some tables exist, don't try to create tables again. -- We could improve by reading the current database schema, comparing with our -- schema and create what is missing (new tables, new columns). if Has_Tables (DB, Config.Get_Database) then Generator.Error ("The database {0} exists", Config.Get_Database); else -- Create the user grant. On MySQL, it is safe to do this several times. Create_User_Grant (DB, Config.Get_Database, Config.Get_Property ("user"), Config.Get_Property ("password")); -- And now create the tables by using the SQL script generated by Dyanmo. Create_Mysql_Tables (Name, Model, Config, Generator); end if; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end; end Create_Database; Model : constant String := Get_Argument; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- 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 GNAT.Command_Line; with GNAT.Expect; with GNAT.OS_Lib; with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with ADO.Drivers.Connections; with ADO.Sessions.Factory; with ADO.Statements; with ADO.Queries; with ADO.Parameters; with System; with Gen.Database.Model; package body Gen.Commands.Database is use GNAT.Command_Line; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database"); -- Check if the database with the given name exists. function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Check if the database with the given name has some tables. function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean; -- Expect filter to print the command output/error procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address); -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String); -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler); -- Create the database identified by the given name. procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String); -- Create the user and grant him access to the database. procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String); -- ------------------------------ -- Check if the database with the given name exists. -- ------------------------------ function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Database_List); Stmt := DB.Create_Statement (Query); Stmt.Execute; while Stmt.Has_Elements loop declare D : constant String := Stmt.Get_String (0); begin if Name = D then return True; end if; end; Stmt.Next; end loop; return False; end Has_Database; -- ------------------------------ -- Check if the database with the given name has some tables. -- ------------------------------ function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Query.Set_Query (Gen.Database.Model.Query_Table_List); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; return Stmt.Has_Elements; end Has_Tables; -- ------------------------------ -- Create the database identified by the given name. -- ------------------------------ procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Creating database '{0}'", Name); Query.Set_Query (Gen.Database.Model.Query_Create_Database); Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; end Create_Database; -- ------------------------------ -- Create the user and grant him access to the database. -- ------------------------------ procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String) is use Ada.Strings.Unbounded; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name); if Password'Length > 0 then Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password); else Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password); end if; Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Bind_Param ("user", ADO.Parameters.Token (User)); if Password'Length > 0 then Stmt.Bind_Param ("password", Password); end if; Stmt.Execute; Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges); Stmt := DB.Create_Statement (Query); Stmt.Execute; end Create_User_Grant; -- ------------------------------ -- Expect filter to print the command output/error -- ------------------------------ procedure Command_Output (Descriptor : in GNAT.Expect.Process_Descriptor'Class; Data : in String; Closure : in System.Address) is pragma Unreferenced (Descriptor, Closure); begin Log.Error ("{0}", Data); end Command_Output; -- ------------------------------ -- Execute the external command <b>Name</b> with the arguments in <b>Args</b> -- and send the content of the file <b>Input</b> to that command. -- ------------------------------ procedure Execute_Command (Name : in String; Args : in GNAT.OS_Lib.Argument_List; Input : in String) is Proc : GNAT.Expect.Process_Descriptor; Status : Integer; Func : constant GNAT.Expect.Filter_Function := Command_Output'Access; Result : GNAT.Expect.Expect_Match; Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => Input, Into => Content); GNAT.Expect.Non_Blocking_Spawn (Descriptor => Proc, Command => Name, Args => Args, Buffer_Size => 4096, Err_To_Out => True); GNAT.Expect.Add_Filter (Descriptor => Proc, Filter => Func, Filter_On => GNAT.Expect.Output); GNAT.Expect.Send (Descriptor => Proc, Str => Ada.Strings.Unbounded.To_String (Content), Add_LF => False, Empty_Buffer => False); GNAT.Expect.Expect (Proc, Result, ".*"); GNAT.Expect.Close (Descriptor => Proc, Status => Status); if Status = 0 then Log.Info ("Database schema created successfully."); else Log.Error ("Error while creating the database schema."); end if; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read {0}", Input); end Execute_Command; -- ------------------------------ -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. -- ------------------------------ procedure Create_Mysql_Tables (Name : in String; Model : in String; Config : in ADO.Drivers.Connections.Configuration; Generator : in out Gen.Generator.Handler) is Database : constant String := Config.Get_Database; Username : constant String := Config.Get_Property ("user"); Password : constant String := Config.Get_Property ("password"); Dir : constant String := Util.Files.Compose (Model, "mysql"); File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql"); begin Log.Info ("Creating database tables using schema '{0}'", File); if not Ada.Directories.Exists (File) then Generator.Error ("SQL file '{0}' does not exist.", File); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Password'Length > 0 then declare Args : GNAT.OS_Lib.Argument_List (1 .. 3); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '("--password=" & Password); Args (3) := new String '(Database); Execute_Command ("mysql", Args, File); end; else declare Args : GNAT.OS_Lib.Argument_List (1 .. 2); begin Args (1) := new String '("--user=" & Username); Args (2) := new String '(Database); Execute_Command ("mysql", Args, File); end; end if; end Create_Mysql_Tables; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model : in String; Database : in String; Username : in String; Password : in String) is Factory : ADO.Sessions.Factory.Session_Factory; Config : ADO.Drivers.Connections.Configuration; Root_Connection : Unbounded_String; Pos : Natural; begin Config.Set_Connection (Database); if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; -- Build a connection string to create the database. Pos := Util.Strings.Index (Database, ':'); Append (Root_Connection, Database (Database'First .. Pos)); Append (Root_Connection, "//"); Append (Root_Connection, Config.Get_Server); if Config.Get_Port > 0 then Append (Root_Connection, ':'); Append (Root_Connection, Util.Strings.Image (Config.Get_Port)); end if; Append (Root_Connection, "/?user="); Append (Root_Connection, Username); if Password'Length > 0 then Append (Root_Connection, "&password="); Append (Root_Connection, Password); end if; Log.Info ("Connecting to {0} for database setup", Root_Connection); -- Initialize the session factory to connect to the -- database defined by root connection (which should allow the database creation). Factory.Create (To_String (Root_Connection)); declare Name : constant String := Generator.Get_Project_Name; DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin -- Create the database only if it does not already exists. if not Has_Database (DB, Config.Get_Database) then Create_Database (DB, Config.Get_Database); end if; -- If some tables exist, don't try to create tables again. -- We could improve by reading the current database schema, comparing with our -- schema and create what is missing (new tables, new columns). if Has_Tables (DB, Config.Get_Database) then Generator.Error ("The database {0} exists", Config.Get_Database); else -- Create the user grant. On MySQL, it is safe to do this several times. Create_User_Grant (DB, Config.Get_Database, Config.Get_Property ("user"), Config.Get_Property ("password")); -- And now create the tables by using the SQL script generated by Dyanmo. Create_Mysql_Tables (Name, Model, Config, Generator); end if; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end; end Create_Database; Model : constant String := Get_Argument; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
Fix log message
Fix log message
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
cd1c418bf999229fb07fb93052d356a6c34cb8d5
src/gen-model-beans.adb
src/gen-model-beans.adb
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- 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 Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- 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 Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Name := Name; declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- 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 Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Set_Name (Name); Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Set_Name (Name); declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
Update to use Get_Location and Set_Name
Update to use Get_Location and Set_Name
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ce664ac4bcfb77a8a706f3857bc28d2297ec50bc
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Implement the Adjust procedure
Implement the Adjust procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0d170acbb75bd9ecb47351732604a9cb01cbbbed
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Make the Kind_Type private
Make the Kind_Type private
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2458e623309f1e2a83279849aabfc0c7d07e7696
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- 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.Strings.Wide_Wide_Unbounded; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- == Attributes == -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List_Type is private; -- Find the attribute with the given name. function Find (List : in Attribute_List_Type; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List_Type) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List_Type) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List_Type); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wide_Wide_String (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List_Type is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List_Type); 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.Strings.Wide_Wide_Unbounded; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- == Attributes == -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List_Type is private; -- Find the attribute with the given name. function Find (List : in Attribute_List_Type; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Wide_Wide_String; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List_Type) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List_Type) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List_Type); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wide_Wide_String (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List_Type is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List_Type); end Wiki.Attributes;
Declare Get_Attribute function returning a Wide_Wide_String
Declare Get_Attribute function returning a Wide_Wide_String
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
67601acbfc984811f36d20a6bb304a840c632b58
regtests/wiki-parsers-tests.adb
regtests/wiki-parsers-tests.adb
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x" & CR & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Wiki.Utils; package body Wiki.Parsers.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " & "href=""http://www.joe.com/item"">name </a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br />b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " & "src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x" & CR & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; end Wiki.Parsers.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
947036335709db933ef938516c89e36c1aaa6182
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; function Get_Parameter (Name : in String) return ADO.Identifier; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is use type ASF.Contexts.Faces.Faces_Context_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Ctx = null then return ADO.NO_IDENTIFIER; else declare P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; end; end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Object.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Object.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
Use the AWA.Helpers.Requests package
Use the AWA.Helpers.Requests package
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fede5516176c4bd5628ddb8e8d0a074728b17b09
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop -- Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); 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. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with GNAT.Regexp; with Security.Controllers; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Policy_Config_Access := new Policy_Config; begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Policy'Unchecked_Access; Policy_Mapper.Set_Context (Reader, Config); 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. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Check the permission using the context operation Has_Permission
Check the permission using the context operation Has_Permission
Ada
apache-2.0
stcarrez/ada-security
c88ad316b37d34bfb537d05ed32b7f495e1d6dad
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- 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.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up", Test_Vote_Up'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2); end; end Test_Vote_Up; end AWA.Votes.Modules.Tests;
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- 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.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up", Test_Vote_Up'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); end; end Test_Vote_Up; end AWA.Votes.Modules.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2bce4ad0c368ef9ac1ca32bf1efaa7b2aa0e76c4
src/gen-artifacts-xmi.ads
src/gen-artifacts-xmi.ads
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with DOM.Core; with Gen.Model.Packages; with Gen.Model.XMI; -- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code -- from an UML XMI description. package Gen.Artifacts.XMI is -- ------------------------------ -- UML XMI artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. overriding procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class); -- Read the UML configuration files that define the pre-defined types, stereotypes -- and other components used by a model. These files are XMI files as well. -- All the XMI files in the UML config directory are read. procedure Read_UML_Configuration (Handler : in out Artifact; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with record Nodes : aliased Gen.Model.XMI.UML_Model; Has_Config : Boolean := False; -- Stereotype which triggers the generation of database table. Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; -- Tag definitions which control the generation. Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access; -- Stereotype which triggers the generation of AWA bean types. Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access; end record; end Gen.Artifacts.XMI;
Add support for the sql type name tag definition
Add support for the sql type name tag definition
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
5bf3393551d9a965af9f4bea52ceaf11fe599336
src/util-serialize-mappers.ads
src/util-serialize-mappers.ads
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Serialize.Contexts; package Util.Serialize.Mappers is Mapping_Error : exception; -- The <b>Field_Error</b> exception can be raised by a mapper to indicate that the field -- that was extracted is invalid. The exception message will be reported as an error message -- and the IO reader will be marked as in error. The IO reader will continue to read and -- process the mappings. Field_Error : exception; -- The <b>Field_Fatal_Error</b> exception is similar to the <b>Field_Error</b> exception. -- However the IO reader will report the error and immediately stop. Field_Fatal_Error : exception; -- ------------------------------ -- Mapping -- ------------------------------ -- The <b>Mapping</b> represents a rule component to establish a mapping -- when reading some format (XML, JSON). type Mapping is abstract tagged limited private; type Mapping_Access is access all Mapping'Class; -- ------------------------------ -- Mapper -- ------------------------------ -- The <b>Mapper</b> represents a node of the mapping tree. The mapping -- tree is walked horizontally to find siblings. It is walked vertically when -- entering or leaving an object. type Mapper is new Ada.Finalization.Limited_Controlled with private; type Mapper_Access is access all Mapper'Class; -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i> -- **/name matches: <i><name>...</name></i>, <b><c><name>...</name></c></b> procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access); procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access); -- Clone the <b>Handler</b> instance and get a copy of that single object. function Clone (Handler : in Mapper) return Mapper_Access; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class); procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String); procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String); -- Find the mapper associated with the given name. -- Returns null if there is no mapper. function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access; function Is_Proxy (Controller : in Mapper) return Boolean; -- Returns true if the mapper is a wildcard node (matches any element). function Is_Wildcard (Controller : in Mapper) return Boolean; -- Returns the mapping name. function Get_Name (Controller : in Mapper) return String; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := ""); private -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Root : in out Mapper_Access; Result : out Mapper_Access); -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access); type Mapping is abstract tagged limited record Mapper : Mapper_Access; Name : Ada.Strings.Unbounded.Unbounded_String; Is_Attribute : Boolean := False; end record; type Mapper is new Ada.Finalization.Limited_Controlled with record Next_Mapping : Mapper_Access := null; First_Child : Mapper_Access := null; Mapper : Mapper_Access := null; Mapping : Mapping_Access := null; Name : Ada.Strings.Unbounded.Unbounded_String; Is_Proxy_Mapper : Boolean := False; Is_Clone : Boolean := False; Is_Wildcard : Boolean := False; Is_Deep_Wildcard : Boolean := False; end record; -- Finalize the object and release any mapping. overriding procedure Finalize (Controller : in out Mapper); end Util.Serialize.Mappers;
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Stacks; with Util.Serialize.IO; with Util.Serialize.Contexts; package Util.Serialize.Mappers is Mapping_Error : exception; -- The <b>Field_Error</b> exception can be raised by a mapper to indicate that the field -- that was extracted is invalid. The exception message will be reported as an error message -- and the IO reader will be marked as in error. The IO reader will continue to read and -- process the mappings. Field_Error : exception; -- The <b>Field_Fatal_Error</b> exception is similar to the <b>Field_Error</b> exception. -- However the IO reader will report the error and immediately stop. Field_Fatal_Error : exception; -- ------------------------------ -- Mapping -- ------------------------------ -- The <b>Mapping</b> represents a rule component to establish a mapping -- when reading some format (XML, JSON). type Mapping is abstract tagged limited private; type Mapping_Access is access all Mapping'Class; -- ------------------------------ -- Mapper -- ------------------------------ -- The <b>Mapper</b> represents a node of the mapping tree. The mapping -- tree is walked horizontally to find siblings. It is walked vertically when -- entering or leaving an object. type Mapper is new Ada.Finalization.Limited_Controlled with private; type Mapper_Access is access all Mapper'Class; -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i> -- **/name matches: <i><name>...</name></i>, <b><c><name>...</name></c></b> procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access); procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access); -- Clone the <b>Handler</b> instance and get a copy of that single object. function Clone (Handler : in Mapper) return Mapper_Access; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class); procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String); procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String); -- Find the mapper associated with the given name. -- Returns null if there is no mapper. function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access; function Is_Proxy (Controller : in Mapper) return Boolean; -- Returns true if the mapper is a wildcard node (matches any element). function Is_Wildcard (Controller : in Mapper) return Boolean; -- Returns the mapping name. function Get_Name (Controller : in Mapper) return String; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := ""); type Processing is new Util.Serialize.Contexts.Context and Util.Serialize.IO.Reader with private; -- Start a document. procedure Start_Document (Stream : in out Processing); -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. procedure Start_Object (Handler : in out Processing; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. procedure Finish_Object (Handler : in out Processing; Name : in String); procedure Start_Array (Handler : in out Processing; Name : in String); procedure Finish_Array (Handler : in out Processing; Name : in String; Count : in Natural); -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Processing; Message : in String); -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. procedure Set_Member (Handler : in out Processing; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); procedure Add_Mapping (Handler : in out Processing; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access); -- Dump the mapping tree on the logger using the INFO log level. procedure Dump (Handler : in Processing'Class; Logger : in Util.Log.Loggers.Logger'Class); private -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Root : in out Mapper_Access; Result : out Mapper_Access); -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access); type Mapping is abstract tagged limited record Mapper : Mapper_Access; Name : Ada.Strings.Unbounded.Unbounded_String; Is_Attribute : Boolean := False; end record; type Mapper is new Ada.Finalization.Limited_Controlled with record Next_Mapping : Mapper_Access := null; First_Child : Mapper_Access := null; Mapper : Mapper_Access := null; Mapping : Mapping_Access := null; Name : Ada.Strings.Unbounded.Unbounded_String; Is_Proxy_Mapper : Boolean := False; Is_Clone : Boolean := False; Is_Wildcard : Boolean := False; Is_Deep_Wildcard : Boolean := False; end record; -- Finalize the object and release any mapping. overriding procedure Finalize (Controller : in out Mapper); -- Implementation limitation: the max number of active mapping nodes MAX_NODES : constant Positive := 10; type Mapper_Access_Array is array (1 .. MAX_NODES) of Serialize.Mappers.Mapper_Access; procedure Push (Handler : in out Processing); -- Pop the context and restore the previous context when leaving an element procedure Pop (Handler : in out Processing); function Find_Mapper (Handler : in Processing; Name : in String) return Util.Serialize.Mappers.Mapper_Access; type Element_Context is record -- The object mapper being process. Object_Mapper : Util.Serialize.Mappers.Mapper_Access; -- The active mapping nodes. Active_Nodes : Mapper_Access_Array; end record; type Element_Context_Access is access all Element_Context; package Context_Stack is new Util.Stacks (Element_Type => Element_Context, Element_Type_Access => Element_Context_Access); type Processing is new Util.Serialize.Contexts.Context and Util.Serialize.IO.Reader with record Error_Flag : Boolean := False; Stack : Context_Stack.Stack; Mapping_Tree : aliased Mappers.Mapper; Current_Mapper : Util.Serialize.Mappers.Mapper_Access; end record; end Util.Serialize.Mappers;
Declare the Processing type to implement the Serialize.IO.Reader interface Declare the operations for Processing to implement the Reader interface
Declare the Processing type to implement the Serialize.IO.Reader interface Declare the operations for Processing to implement the Reader interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f39eb1710e10c4549717aacb8f9c34eeeb31b32b
awa/src/awa-services-filters.adb
awa/src/awa-services-filters.adb
----------------------------------------------------------------------- -- awa-services-filters -- Setup service context in request processing flow -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Applications; with AWA.Users.Principals; with ASF.Principals; package body AWA.Services.Filters is -- ------------------------------ -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- Before passing the control to the next filter, initialize the service -- context to give access to the current application, current user and -- manage possible transaction rollbacks. -- ------------------------------ procedure Do_Filter (F : in Service_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is pragma Unreferenced (F); use type ASF.Principals.Principal_Access; App : constant ASF.Servlets.Servlet_Registry_Access := ASF.Servlets.Get_Servlet_Context (Chain); P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal; Context : aliased AWA.Services.Contexts.Service_Context; Principal : AWA.Users.Principals.Principal_Access; Application : AWA.Applications.Application_Access; begin -- Get the user if P /= null and then P.all in AWA.Users.Principals.Principal'Class then Principal := AWA.Users.Principals.Principal'Class (P.all)'Access; else Principal := null; end if; -- Get the application if App.all in AWA.Applications.Application'Class then Application := AWA.Applications.Application'Class (App.all)'Access; else Application := null; end if; -- Setup the service context. Context.Set_Context (Application, Principal); -- Give the control to the next chain up to the servlet. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); -- By leaving this scope, the active database transactions are rollbacked -- (finalization of Service_Context) end Do_Filter; end AWA.Services.Filters;
----------------------------------------------------------------------- -- awa-services-filters -- Setup service context in request processing flow -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Applications; with AWA.Users.Principals; with ASF.Principals; package body AWA.Services.Filters is -- ------------------------------ -- The Do_Filter method of the Filter is called by the container each time -- a request/response pair is passed through the chain due to a client request -- for a resource at the end of the chain. The Filter_Chain passed in to this -- method allows the Filter to pass on the request and response to the next -- entity in the chain. -- -- Before passing the control to the next filter, initialize the service -- context to give access to the current application, current user and -- manage possible transaction rollbacks. -- ------------------------------ procedure Do_Filter (F : in Service_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is pragma Unreferenced (F); use type ASF.Principals.Principal_Access; App : constant ASF.Servlets.Servlet_Registry_Access := ASF.Servlets.Get_Servlet_Context (Chain); P : constant ASF.Principals.Principal_Access := Request.Get_User_Principal; Context : aliased AWA.Services.Contexts.Service_Context; Principal : AWA.Users.Principals.Principal_Access; Application : AWA.Applications.Application_Access; begin -- Get the user if P /= null and then P.all in AWA.Users.Principals.Principal'Class then Principal := AWA.Users.Principals.Principal'Class (P.all)'Access; else Principal := null; end if; -- Get the application if App.all in AWA.Applications.Application'Class then Application := AWA.Applications.Application'Class (App.all)'Access; else Application := null; end if; -- Setup the service context. Context.Set_Context (Application, Principal); -- Give the control to the next chain up to the servlet. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); -- By leaving this scope, the active database transactions are rollbacked -- (finalization of Service_Context) end Do_Filter; end AWA.Services.Filters;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
1092eb7fbdd61057b37c91b2114b33edeca2cefd
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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- 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; Tag : Wiki.Nodes.Html_Tag_Type; 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); Tag := Wiki.Nodes.Find_Tag (To_Wide_Wide_String (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, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, 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 while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; 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; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I))); 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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- 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; Tag : Wiki.Html_Tag; 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); Tag := Wiki.Find_Tag (To_Wide_Wide_String (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, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, 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 while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; 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; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Move the Html_Tag type from Wiki.Nodes to Wiki package
Move the Html_Tag type from Wiki.Nodes to Wiki package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4a54d18fb9e03dc9c4baa307cf6016acbce1b7a5
src/asf-navigations-mappers.ads
src/asf-navigations-mappers.ads
----------------------------------------------------------------------- -- asf-navigations-mappers -- Read XML navigation files -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with EL.Contexts; -- The <b>ASF.Navigations.Reader</b> package defines an XML mapper that can be used -- to read the XML navigation files. package ASF.Navigations.Mappers is type Navigation_Case_Fields is (FROM_VIEW_ID, OUTCOME, ACTION, TO_VIEW, REDIRECT, CONDITION, CONTENT, CONTENT_TYPE, NAVIGATION_CASE, NAVIGATION_RULE); -- ------------------------------ -- Navigation Config Reader -- ------------------------------ -- When reading and parsing the XML navigation file, the <b>Nav_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of the navigation case element is reached, -- the new navigation case is inserted in the navigation handler. type Nav_Config is limited record Outcome : Util.Beans.Objects.Object; Action : Util.Beans.Objects.Object; To_View : Util.Beans.Objects.Object; From_View : Util.Beans.Objects.Object; Redirect : Boolean := False; Condition : Util.Beans.Objects.Object; Content : Util.Beans.Objects.Object; Content_Type : Util.Beans.Objects.Object; Context : EL.Contexts.ELContext_Access; Handler : Navigation_Handler_Access; end record; type Nav_Config_Access is access all Nav_Config; -- Save in the navigation config object the value associated with the given field. -- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule -- that was collected in the navigation handler. procedure Set_Member (N : in out Nav_Config; Field : in Navigation_Case_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the navigation rules. generic Reader : in out Util.Serialize.IO.XML.Parser; Handler : in Navigation_Handler_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Nav_Config; end Reader_Config; private -- Reset the navigation config before parsing a new rule. procedure Reset (N : in out Nav_Config); package Navigation_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Nav_Config, Element_Type_Access => Nav_Config_Access, Fields => Navigation_Case_Fields, Set_Member => Set_Member); end ASF.Navigations.Mappers;
----------------------------------------------------------------------- -- asf-navigations-mappers -- Read XML navigation files -- Copyright (C) 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with EL.Contexts; -- The <b>ASF.Navigations.Reader</b> package defines an XML mapper that can be used -- to read the XML navigation files. package ASF.Navigations.Mappers is type Navigation_Case_Fields is (FROM_VIEW_ID, OUTCOME, ACTION, TO_VIEW, REDIRECT, CONDITION, CONTENT, CONTENT_TYPE, NAVIGATION_CASE, NAVIGATION_RULE); -- ------------------------------ -- Navigation Config Reader -- ------------------------------ -- When reading and parsing the XML navigation file, the <b>Nav_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of the navigation case element is reached, -- the new navigation case is inserted in the navigation handler. type Nav_Config is limited record Outcome : Util.Beans.Objects.Object; Action : Util.Beans.Objects.Object; To_View : Util.Beans.Objects.Object; From_View : Util.Beans.Objects.Object; Redirect : Boolean := False; Condition : Util.Beans.Objects.Object; Content : Util.Beans.Objects.Object; Content_Type : Util.Beans.Objects.Object; Context : EL.Contexts.ELContext_Access; Handler : Navigation_Handler_Access; end record; type Nav_Config_Access is access all Nav_Config; -- Save in the navigation config object the value associated with the given field. -- When the <b>NAVIGATION_CASE</b> field is reached, insert the new navigation rule -- that was collected in the navigation handler. procedure Set_Member (N : in out Nav_Config; Field : in Navigation_Case_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the navigation rules. generic Mapper : in out Util.Serialize.Mappers.Processing; Handler : in Navigation_Handler_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Nav_Config; end Reader_Config; private -- Reset the navigation config before parsing a new rule. procedure Reset (N : in out Nav_Config); package Navigation_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Nav_Config, Element_Type_Access => Nav_Config_Access, Fields => Navigation_Case_Fields, Set_Member => Set_Member); end ASF.Navigations.Mappers;
Update the Reader_Config to use the new parser/mapper interface
Update the Reader_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2ae972b8a95865a33f63b7955a2d0d2dde9f682c
awa/plugins/awa-questions/src/awa-questions-beans.ads
awa/plugins/awa-questions/src/awa-questions-beans.ads
----------------------------------------------------------------------- -- 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 Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Questions.Modules; with AWA.Questions.Models; with AWA.Tags.Beans; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Service : Modules.Question_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Create or save the question. procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record Service : Modules.Question_Module_Access := null; Question : AWA.Questions.Models.Question_Ref; end record; type Answer_Bean_Access is access all Answer_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Create or save the answer. procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the answer bean instance. function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Question_List_Bean is limited new Util.Beans.Basic.Bean with record Questions : aliased AWA.Questions.Models.Question_Info_List_Bean; Service : Modules.Question_Module_Access := null; Tag : Ada.Strings.Unbounded.Unbounded_String; Tags : AWA.Tags.Beans.Entity_Tag_Map; Questions_Bean : AWA.Questions.Models.Question_Info_List_Bean_Access; end record; type Question_List_Bean_Access is access all Question_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of question. If a tag was set, filter the list of questions with the tag. procedure Load_List (Into : in out Question_List_Bean); -- 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; type Question_Display_Bean is new Util.Beans.Basic.Bean with record Service : Modules.Question_Module_Access := null; -- List of answers associated with the question. Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean; Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access; -- The question. Question : aliased AWA.Questions.Models.Question_Display_Info; Question_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Display_Bean_Access is access all Question_Display_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Question_Display_Bean bean instance. function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Helpers.Beans; with ADO; with AWA.Questions.Modules; with AWA.Questions.Models; with AWA.Tags.Beans; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Service : Modules.Question_Module_Access := null; Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Load question. overriding procedure Load (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create or save the question. overriding procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. overriding procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record Service : Modules.Question_Module_Access := null; Question_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Question : AWA.Questions.Models.Question_Ref; end record; type Answer_Bean_Access is access all Answer_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object; -- 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); -- Load the answer. overriding procedure Load (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create or save the answer. overriding procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. overriding procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the answer bean instance. function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Answer_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Answer_Bean, Element_Access => Answer_Bean_Access); type Question_List_Bean is limited new AWA.Questions.Models.Question_List_Bean with record Questions : aliased AWA.Questions.Models.Question_Info_List_Bean; Service : Modules.Question_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Questions_Bean : AWA.Questions.Models.Question_Info_List_Bean_Access; end record; type Question_List_Bean_Access is access all Question_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of question. If a tag was set, filter the list of questions with the tag. procedure Load_List (Into : in out Question_List_Bean); -- Load the list of questions. overriding procedure Load (Bean : in out Question_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- 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; type Question_Display_Bean is new AWA.Questions.Models.Question_Display_Bean with record Service : Modules.Question_Module_Access := null; Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of answers associated with the question. Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean; Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access; -- The question. Question : aliased AWA.Questions.Models.Question_Display_Info; Question_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The anwswer bean. Answer : Answer_Bean_Access; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Display_Bean_Access is access all Question_Display_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the question and its answers. overriding procedure Load (Bean : in out Question_Display_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Question_Display_Bean bean instance. function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
Add Load bean operations to load the list, question, answer
Add Load bean operations to load the list, question, answer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa