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
7622568cdc25bde4ea31851bc02f1674f58cfd30
mat/src/events/mat-events-probes.adb
mat/src/events/mat-events-probes.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d1284b9b5791ac9490c411ffd97b353f0efd76fd
src/orka/implementation/glfw/orka-windows-glfw.adb
src/orka/implementation/glfw/orka-windows-glfw.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; package body Orka.Windows.GLFW is procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Ada.Text_IO.Put_Line ("Error occured (" & Standard.Glfw.Errors.Kind'Image (Code) & "): " & Description); end Print_Error; function Initialize (Major, Minor : Natural; Debug : Boolean := False) return Active_GLFW'Class is begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Major, Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Profile (Standard.Glfw.Windows.Context.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Debug); return Active_GLFW'(Ada.Finalization.Limited_Controlled with Debug => Debug, Finalized => False); end Initialize; overriding procedure Finalize (Object : in out Active_GLFW) is begin if not Object.Finalized then if Object.Debug then Ada.Text_IO.Put_Line ("Shutting down GLFW"); end if; Standard.Glfw.Shutdown; Object.Finalized := True; end if; end Finalize; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Object.Destroy; Object.Finalized := True; end if; end Finalize; function Create_Window (Width, Height : Positive; Samples : Natural := 0; Visible, Resizable : Boolean := True) return Window'Class is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), ""); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Windows.Context.Make_Current (Reference); end; end return; end Create_Window; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : in out GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is begin Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is use type GL.Types.Double; begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; with Glfw.Errors; with Glfw.Windows.Context; with Glfw.Windows.Hints; with Orka.Inputs.GLFW; package body Orka.Windows.GLFW is procedure Print_Error (Code : Standard.Glfw.Errors.Kind; Description : String) is begin Ada.Text_IO.Put_Line ("Error occured (" & Standard.Glfw.Errors.Kind'Image (Code) & "): " & Description); end Print_Error; function Initialize (Major, Minor : Natural; Debug : Boolean := False) return Active_GLFW'Class is begin -- Initialize GLFW Standard.Glfw.Errors.Set_Callback (Print_Error'Access); Standard.Glfw.Init; -- Initialize OpenGL context Standard.Glfw.Windows.Hints.Set_Minimum_OpenGL_Version (Major, Minor); Standard.Glfw.Windows.Hints.Set_Forward_Compat (True); Standard.Glfw.Windows.Hints.Set_Profile (Standard.Glfw.Windows.Context.Core_Profile); Standard.Glfw.Windows.Hints.Set_Debug_Context (Debug); return Active_GLFW'(Ada.Finalization.Limited_Controlled with Debug => Debug, Finalized => False); end Initialize; overriding procedure Finalize (Object : in out Active_GLFW) is begin if not Object.Finalized then if Object.Debug then Ada.Text_IO.Put_Line ("Shutting down GLFW"); end if; Standard.Glfw.Shutdown; Object.Finalized := True; end if; end Finalize; overriding procedure Finalize (Object : in out GLFW_Window) is begin if not Object.Finalized then Object.Destroy; Object.Finalized := True; end if; end Finalize; function Create_Window (Width, Height : Positive; Samples : Natural := 0; Visible, Resizable : Boolean := True) return Window'Class is package Windows renames Standard.Glfw.Windows; begin return Result : GLFW_Window := GLFW_Window'(Windows.Window with Input => Inputs.GLFW.Create_Pointer_Input, Finalized => False, others => <>) do declare Reference : constant Windows.Window_Reference := Windows.Window (Window'Class (Result))'Access; begin Windows.Hints.Set_Visible (Visible); Windows.Hints.Set_Resizable (Resizable); Windows.Hints.Set_Samples (Samples); Reference.Init (Standard.Glfw.Size (Width), Standard.Glfw.Size (Height), ""); Inputs.GLFW.GLFW_Pointer_Input (Result.Input.all).Set_Window (Reference); declare Width, Height : Standard.Glfw.Size; begin Reference.Get_Framebuffer_Size (Width, Height); Result.Framebuffer_Size_Changed (Natural (Width), Natural (Height)); end; -- Callbacks Reference.Enable_Callback (Windows.Callbacks.Close); Reference.Enable_Callback (Windows.Callbacks.Mouse_Button); Reference.Enable_Callback (Windows.Callbacks.Mouse_Position); Reference.Enable_Callback (Windows.Callbacks.Mouse_Scroll); Reference.Enable_Callback (Windows.Callbacks.Key); Reference.Enable_Callback (Windows.Callbacks.Framebuffer_Size); Windows.Context.Make_Current (Reference); end; end return; end Create_Window; overriding function Pointer_Input (Object : GLFW_Window) return Inputs.Pointer_Input_Ptr is (Object.Input); overriding function Width (Object : GLFW_Window) return Positive is (Object.Width); overriding function Height (Object : GLFW_Window) return Positive is (Object.Height); overriding procedure Set_Title (Object : in out GLFW_Window; Value : String) is begin Standard.Glfw.Windows.Window (Object)'Access.Set_Title (Value); end Set_Title; overriding procedure Close (Object : in out GLFW_Window) is begin Object.Set_Should_Close (True); end Close; overriding function Should_Close (Object : in out GLFW_Window) return Boolean is begin return Standard.Glfw.Windows.Window (Object)'Access.Should_Close; end Should_Close; overriding procedure Process_Input (Object : in out GLFW_Window) is begin Standard.Glfw.Input.Poll_Events; -- Update position of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Position (Object.Position_X, Object.Position_Y); -- Update scroll offset of mouse Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Scroll_Offset (Object.Scroll_X, Object.Scroll_Y); end Process_Input; overriding procedure Swap_Buffers (Object : in out GLFW_Window) is begin Standard.Glfw.Windows.Context.Swap_Buffers (Object'Access); end Swap_Buffers; overriding procedure Close_Requested (Object : not null access GLFW_Window) is begin -- TODO Call Object.Set_Should_Close (False); if certain conditions are not met null; end Close_Requested; overriding procedure Key_Changed (Object : not null access GLFW_Window; Key : Standard.Glfw.Input.Keys.Key; Scancode : Standard.Glfw.Input.Keys.Scancode; Action : Standard.Glfw.Input.Keys.Action; Mods : Standard.Glfw.Input.Keys.Modifiers) is use Standard.Glfw.Input.Keys; begin if Key = Escape and Action = Press then Object.Set_Should_Close (True); end if; -- TODO Add Button_Input object end Key_Changed; overriding procedure Mouse_Position_Changed (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Coordinate) is begin Object.Position_X := GL.Types.Double (X); Object.Position_Y := GL.Types.Double (Y); end Mouse_Position_Changed; overriding procedure Mouse_Scrolled (Object : not null access GLFW_Window; X, Y : Standard.Glfw.Input.Mouse.Scroll_Offset) is use type GL.Types.Double; begin Object.Scroll_X := Object.Scroll_X + GL.Types.Double (X); Object.Scroll_Y := Object.Scroll_Y + GL.Types.Double (Y); end Mouse_Scrolled; overriding procedure Mouse_Button_Changed (Object : not null access GLFW_Window; Button : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State; Mods : Standard.Glfw.Input.Keys.Modifiers) is begin Inputs.GLFW.GLFW_Pointer_Input (Object.Input.all).Set_Button_State (Button, State); end Mouse_Button_Changed; overriding procedure Framebuffer_Size_Changed (Object : not null access GLFW_Window; Width, Height : Natural) is begin Object.Width := Width; Object.Height := Height; end Framebuffer_Size_Changed; end Orka.Windows.GLFW;
Remove useless "use type" clause
Remove useless "use type" clause Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f2cd33a6406a134ce13ca97f5d97c9bf0d92cd17
src/babel-files-maps.adb
src/babel-files-maps.adb
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Babel.Files.Maps is -- ------------------------------ -- Find the file with the given name in the file map. -- ------------------------------ function Find (From : in File_Map; Name : in String) return File_Cursor is begin return From.Find (Key => Name'Unrestricted_Access); end Find; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ procedure Add_File (Into : in out Differential_Container; Element : in File_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Files.Insert (Element.Name'Unrestricted_Access, Element); end if; end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type) is use type ADO.Identifier; begin if Element.Id = ADO.NO_IDENTIFIER then Into.Files.Children (Element.Name'Unrestricted_Access, Element); end if; end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ function Create (Into : in Differential_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return File_Type is begin return Find (From.Files, Name); end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ function Find (From : in Differential_Container; Name : in String) return Directory_Type is begin return Find (From.Children, Name); end Find; end Babel.Files.Maps;
Implement the new operations for Differential_Container type
Implement the new operations for Differential_Container type
Ada
apache-2.0
stcarrez/babel
64b4b66044ff1820afd4a01e09159a8d3d5e0cbf
regtests/ado-tests.ads
regtests/ado-tests.ads
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record I1 : Integer; I2 : Integer; end record; procedure Set_Up (T : in out Test); procedure Test_Load (T : in out Test); procedure Test_Create_Load (T : in out Test); procedure Test_Not_Open (T : in out Test); procedure Test_Allocate (T : in out Test); procedure Test_Create_Save (T : in out Test); procedure Test_Perf_Create_Save (T : in out Test); procedure Test_Delete_All (T : in out Test); -- Test string insert. procedure Test_String (T : in out Test); -- Test blob insert. procedure Test_Blob (T : in out Test); -- Test the To_Object and To_Identifier operations. procedure Test_Identifier_To_Object (T : in out Test); end ADO.Tests;
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record I1 : Integer; I2 : Integer; end record; procedure Set_Up (T : in out Test); procedure Test_Load (T : in out Test); procedure Test_Create_Load (T : in out Test); procedure Test_Not_Open (T : in out Test); procedure Test_Allocate (T : in out Test); procedure Test_Create_Save (T : in out Test); procedure Test_Perf_Create_Save (T : in out Test); procedure Test_Delete_All (T : in out Test); -- Test string insert. procedure Test_String (T : in out Test); -- Test blob insert. procedure Test_Blob (T : in out Test); -- Test the To_Object and To_Identifier operations. procedure Test_Identifier_To_Object (T : in out Test); -- Test database reload. procedure Test_Reload (T : in out Test); end ADO.Tests;
Add Test_Reload procedure to check the new generated Reload procedure
Add Test_Reload procedure to check the new generated Reload procedure
Ada
apache-2.0
stcarrez/ada-ado
30be4b03bc7ac78981f9554bd472429adc0e6d6a
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- 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 Ada.Strings.Unbounded; with Ada.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; Stream.Write ('"'); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ("""null"""); when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("""true"""); else Stream.Write ("""false"""); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (","); end if; Stream.Column := Stream.Column + 1; Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (","); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Parser'Class (Handler).Finish_Object (""); end if; Parser'Class (Handler).Start_Object (""); end if; Handler.Row := Row; Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; Context : Element_Context_Access; begin Context_Stack.Push (Handler.Stack); Context := Context_Stack.Current (Handler.Stack); Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Context_Stack.Pop (Handler.Stack); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Implement the new Write_Attribute, Write_Cell operations
Implement the new Write_Attribute, Write_Cell operations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fa7bfbbede3b30e3ae52a8033ed22655a0f1027b
awa/plugins/awa-mail/src/awa-mail-beans.ads
awa/plugins/awa-mail/src/awa-mail-beans.ads
----------------------------------------------------------------------- -- awa-mail-beans -- Beans for mail module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Objects.Maps; with AWA.Events; with AWA.Mail.Modules; package AWA.Mail.Beans is type Mail_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Mail.Modules.Mail_Module_Access := null; Props : Util.Beans.Objects.Maps.Map; Template : Ada.Strings.Unbounded.Unbounded_String; end record; type Mail_Bean_Access is access all Mail_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Mail_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Mail_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Mail_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Format and send the mail. procedure Send_Mail (Bean : in out Mail_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the mail bean instance. function Create_Mail_Bean (Module : in AWA.Mail.Modules.Mail_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Mail.Beans;
----------------------------------------------------------------------- -- awa-mail-beans -- Beans for mail module -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Objects.Maps; with AWA.Events; with AWA.Mail.Modules; package AWA.Mail.Beans is type Mail_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Mail.Modules.Mail_Module_Access := null; Props : Util.Beans.Objects.Maps.Map; Template : Ada.Strings.Unbounded.Unbounded_String; Params : Util.Beans.Objects.Maps.Map; end record; type Mail_Bean_Access is access all Mail_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Mail_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Mail_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Mail_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Format and send the mail. procedure Send_Mail (Bean : in out Mail_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the mail bean instance. function Create_Mail_Bean (Module : in AWA.Mail.Modules.Mail_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Mail.Beans;
Add the Params member in the Mail_Bean record
Add the Params member in the Mail_Bean record
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4057cec392c0657902eac415274b2d6ed3a6246d
awa/plugins/awa-setup/src/awa-commands-setup.adb
awa/plugins/awa-setup/src/awa-commands-setup.adb
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find_Application (Name : in String); Count : Natural := 0; Selected : Application_Access; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if URI (URI'First + 1 .. URI'Last) = Name then Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find_Application (Name : in String); procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Disable; if URI (URI'First + 1 .. URI'Last) = Name then if App.all in Application'Class then Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Enable; App.Start; end Enable_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Configure_Server (Context); Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command_Drivers.WS.Remove_Application (S'Unchecked_Access); Command.Configure_Applications (Context); Command_Drivers.WS.Iterate (Enable_Application'Access); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
Fix the setup command to disable all applications before the setup and enable and start them afterward
Fix the setup command to disable all applications before the setup and enable and start them afterward
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
33b906939d42b19c22defa005d61409ba34716cc
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- <ul> -- <li>An instance of the security context is declared within a function/procedure as -- a local variable -- <li>This instance will be associated with the current thread through a task attribute -- <li>The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- <li>To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- <li>The <b>Has_Permission<b> will first look in a small cache stored in the security context. -- <li>When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- <li>The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- <li>The result produced by the security controller is then saved in the local cache. -- </ul> package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Permissions.Principal_Access); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Permissions.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- * This instance will be associated with the current thread through a task attribute -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- * The <b>Has_Permission<b> will first look in a small cache stored in the security context. -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Permissions.Principal_Access); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Permissions.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
Update the documentation style
Update the documentation style
Ada
apache-2.0
Letractively/ada-security
1666a4c9850965fab00aade4db31a3596dd51734
src/ado-drivers.adb
src/ado-drivers.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.IO_Exceptions; package body ADO.Drivers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.IO_Exceptions; package body ADO.Drivers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Returns true if the global configuration property is set to true/on. -- ------------------------------ function Is_On (Name : in String) return Boolean is Value : constant String := Global_Config.Get (Name, ""); begin return Value = "on" or Value = "true" or Value = "1"; end Is_On; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
Implement Is_On function
Implement Is_On function
Ada
apache-2.0
stcarrez/ada-ado
4ec6dff628af77260428632c99bcf6bfe0459e1e
testutil/ahven/util-xunit.ads
testutil/ahven/util-xunit.ads
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- 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 Ahven; with Ahven.Framework; with Ahven.Results; with Ada.Strings.Unbounded; with GNAT.Source_Info; -- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil -- library. This implementation exposes an implementation on top of Ahven. -- -- Ahven is written by Tero Koskinen and licensed under permissive ISC license. -- See http://ahven.stronglytyped.org/ package Util.XUnit is use Ada.Strings.Unbounded; type Status is (Success, Failure); subtype Message_String is String; subtype Test_Suite is Ahven.Framework.Test_Suite; type Access_Test_Suite is access all Test_Suite; type Test_Access is access all Ahven.Framework.Test_Case'Class; type Test_Object; type Test_Object_Access is access all Test_Object; type Test_Object is record Test : Test_Access; Next : Test_Object_Access; end record; -- Register a test object in the test suite. procedure Register (T : in Test_Object_Access); -- Build a message from a string (Adaptation for AUnit API). function Format (S : in String) return Message_String; -- Build a message with the source and line number. function Build_Message (Message : in String; Source : in String; Line : in Natural) return String; -- ------------------------------ -- A simple test case -- ------------------------------ type Test_Case is abstract new Ahven.Framework.Test_Case with null record; overriding procedure Initialize (T : in out Test_Case); procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line); -- Return the name of the test case. overriding function Get_Name (T : Test_Case) return String; -- Test case name (this is the AUnit function that must be implemented). function Name (T : in Test_Case) return Message_String is abstract; -- Perform the test (AUnit function to implement). procedure Run_Test (T : in out Test_Case) is abstract; -- ------------------------------ -- A test with fixture -- ------------------------------ type Test is new Ahven.Framework.Test_Case with null record; -- Check that the value matches what we expect. procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Report passes, skips, failures, and errors from the result collection. procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status); end Util.XUnit;
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- Copyright (C) 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ahven; with Ahven.Framework; with Ahven.Results; with Ada.Strings.Unbounded; with GNAT.Source_Info; -- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil -- library. This implementation exposes an implementation on top of Ahven. -- -- Ahven is written by Tero Koskinen and licensed under permissive ISC license. -- See http://ahven.stronglytyped.org/ package Util.XUnit is type Status is (Success, Failure); subtype Message_String is String; subtype Test_Suite is Ahven.Framework.Test_Suite; type Access_Test_Suite is access all Test_Suite; type Test_Access is access all Ahven.Framework.Test_Case'Class; type Test_Object; type Test_Object_Access is access all Test_Object; type Test_Object is record Test : Test_Access; Next : Test_Object_Access; end record; -- Register a test object in the test suite. procedure Register (T : in Test_Object_Access); -- Build a message from a string (Adaptation for AUnit API). function Format (S : in String) return Message_String; -- Build a message with the source and line number. function Build_Message (Message : in String; Source : in String; Line : in Natural) return String; -- ------------------------------ -- A simple test case -- ------------------------------ type Test_Case is abstract new Ahven.Framework.Test_Case with null record; overriding procedure Initialize (T : in out Test_Case); procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line); -- Return the name of the test case. overriding function Get_Name (T : Test_Case) return String; -- Test case name (this is the AUnit function that must be implemented). function Name (T : in Test_Case) return Message_String is abstract; -- Perform the test (AUnit function to implement). procedure Run_Test (T : in out Test_Case) is abstract; -- ------------------------------ -- A test with fixture -- ------------------------------ type Test is new Ahven.Framework.Test_Case with null record; -- Check that the value matches what we expect. procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Report passes, skips, failures, and errors from the result collection. procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status); end Util.XUnit;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ef8e332bed925ce6de811e614066eb6053a3f28e
orka_transforms/src/orka-transforms-simd_matrices.adb
orka_transforms/src/orka-transforms-simd_matrices.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Matrices is package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Diagonal (Elements : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin for Index in Elements'Range loop Result (Index) (Index) := Elements (Index); end loop; return Result; end Diagonal; function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type is (Matrix (X) (X), Matrix (Y) (Y), Matrix (Z) (Z), Matrix (W) (W)); function Trace (Matrix : Matrix_Type) return Element_Type is (Vectors.Sum (Main_Diagonal (Matrix))); function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type is Result : Vector_Type; begin for Column in Right'Range loop Result (Column) := Vectors.Dot (Left, Right (Column)); end loop; return Result; end "*"; function Outer (Left, Right : Vector_Type) return Matrix_Type is use Vectors; Result : Matrix_Type; begin for Index in Right'Range loop Result (Index) := Right (Index) * Left; end loop; return Result; end Outer; ---------------------------------------------------------------------------- function T (Offset : Vectors.Point) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Vector_Type (Offset); return Result; end T; function T (Offset : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Offset; Result (W) (W) := 1.0; return Result; end T; function Rx (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (Y) := (0.0, CA, SA, 0.0); Result (Z) := (0.0, -SA, CA, 0.0); return Result; end Rx; function Ry (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, 0.0, -SA, 0.0); Result (Z) := (SA, 0.0, CA, 0.0); return Result; end Ry; function Rz (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, SA, 0.0, 0.0); Result (Y) := (-SA, CA, 0.0, 0.0); return Result; end Rz; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); MCA : constant Element_Type := 1.0 - CA; MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y); MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z); MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z); RXSA : constant Element_Type := Axis (X) * SA; RYSA : constant Element_Type := Axis (Y) * SA; RZSA : constant Element_Type := Axis (Z) * SA; R11 : constant Element_Type := CA + MCA * Axis (X)**2; R12 : constant Element_Type := MCARXY + RZSA; R13 : constant Element_Type := MCARXZ - RYSA; R21 : constant Element_Type := MCARXY - RZSA; R22 : constant Element_Type := CA + MCA * Axis (Y)**2; R23 : constant Element_Type := MCARYZ + RXSA; R31 : constant Element_Type := MCARXZ + RYSA; R32 : constant Element_Type := MCARYZ - RXSA; R33 : constant Element_Type := CA + MCA * Axis (Z)**2; Result : Matrix_Type; begin Result (X) := (R11, R12, R13, 0.0); Result (Y) := (R21, R22, R23, 0.0); Result (Z) := (R31, R32, R33, 0.0); Result (W) := (0.0, 0.0, 0.0, 1.0); return Result; end R; function R (Quaternion : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 1.0 - 2.0 * (Quaternion (Y) * Quaternion (Y) + Quaternion (Z) * Quaternion (Z)); Result (X) (Y) := 2.0 * (Quaternion (X) * Quaternion (Y) - Quaternion (Z) * Quaternion (W)); Result (X) (Z) := 2.0 * (Quaternion (X) * Quaternion (Z) + Quaternion (Y) * Quaternion (W)); Result (Y) (X) := 2.0 * (Quaternion (X) * Quaternion (Y) + Quaternion (Z) * Quaternion (W)); Result (Y) (Y) := 1.0 - 2.0 * (Quaternion (X) * Quaternion (X) + Quaternion (Z) * Quaternion (Z)); Result (Y) (Z) := 2.0 * (Quaternion (Y) * Quaternion (Z) - Quaternion (X) * Quaternion (W)); Result (Z) (X) := 2.0 * (Quaternion (X) * Quaternion (Z) - Quaternion (Y) * Quaternion (W)); Result (Z) (Y) := 2.0 * (Quaternion (Y) * Quaternion (Z) + Quaternion (X) * Quaternion (W)); Result (Z) (Z) := 1.0 - 2.0 * (Quaternion (X) * Quaternion (X) + Quaternion (Y) * Quaternion (Y)); return Result; end R; function S (Factors : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := Factors (X); Result (Y) (Y) := Factors (Y); Result (Z) (Z) := Factors (Z); return Result; end S; ---------------------------------------------------------------------------- function FOV (Width, Distance : Element_Type) return Element_Type is (2.0 * EF.Arctan (Width / (2.0 * Distance))); function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Z_Far / (Z_Near - Z_Far); Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far); Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Finite_Perspective; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Element_Type (-1.0); Result (W) (Z) := -Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective; function Infinite_Perspective_Reversed_Z (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [1, 0] instead of [-1 , 1] Result (Z) (Z) := Element_Type (0.0); Result (W) (Z) := Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective_Reversed_Z; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 2.0 / X_Mag; Result (Y) (Y) := 2.0 / Y_Mag; -- Depth normalized to [0, 1] instead of [-1, 1] Result (Z) (Z) := -1.0 / (Z_Far - Z_Near); Result (W) (Z) := -Z_Near / (Z_Far - Z_Near); return Result; end Orthographic; end Orka.Transforms.SIMD_Matrices;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Matrices is package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Diagonal (Elements : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin for Index in Elements'Range loop Result (Index) (Index) := Elements (Index); end loop; return Result; end Diagonal; function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type is (Matrix (X) (X), Matrix (Y) (Y), Matrix (Z) (Z), Matrix (W) (W)); function Trace (Matrix : Matrix_Type) return Element_Type is (Vectors.Sum (Main_Diagonal (Matrix))); function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type is Result : Vector_Type; begin for Column in Right'Range loop Result (Column) := Vectors.Dot (Left, Right (Column)); end loop; return Result; end "*"; function Outer (Left, Right : Vector_Type) return Matrix_Type is use Vectors; Result : Matrix_Type; begin for Index in Right'Range loop Result (Index) := Right (Index) * Left; end loop; return Result; end Outer; ---------------------------------------------------------------------------- function T (Offset : Vectors.Point) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Vector_Type (Offset); return Result; end T; function T (Offset : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Offset; Result (W) (W) := 1.0; return Result; end T; function Rx (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (Y) := (0.0, CA, SA, 0.0); Result (Z) := (0.0, -SA, CA, 0.0); return Result; end Rx; function Ry (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, 0.0, -SA, 0.0); Result (Z) := (SA, 0.0, CA, 0.0); return Result; end Ry; function Rz (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, SA, 0.0, 0.0); Result (Y) := (-SA, CA, 0.0, 0.0); return Result; end Rz; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); MCA : constant Element_Type := 1.0 - CA; MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y); MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z); MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z); RXSA : constant Element_Type := Axis (X) * SA; RYSA : constant Element_Type := Axis (Y) * SA; RZSA : constant Element_Type := Axis (Z) * SA; R11 : constant Element_Type := CA + MCA * Axis (X)**2; R12 : constant Element_Type := MCARXY + RZSA; R13 : constant Element_Type := MCARXZ - RYSA; R21 : constant Element_Type := MCARXY - RZSA; R22 : constant Element_Type := CA + MCA * Axis (Y)**2; R23 : constant Element_Type := MCARYZ + RXSA; R31 : constant Element_Type := MCARXZ + RYSA; R32 : constant Element_Type := MCARYZ - RXSA; R33 : constant Element_Type := CA + MCA * Axis (Z)**2; Result : Matrix_Type; begin Result (X) := (R11, R12, R13, 0.0); Result (Y) := (R21, R22, R23, 0.0); Result (Z) := (R31, R32, R33, 0.0); Result (W) := (0.0, 0.0, 0.0, 1.0); return Result; end R; function R (Quaternion : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; Q_X : constant Element_Type := Quaternion (X); Q_Y : constant Element_Type := Quaternion (Y); Q_Z : constant Element_Type := Quaternion (Z); Q_W : constant Element_Type := Quaternion (W); S : constant := 2.0; -- S = 2 / Norm (Quaternion) begin Result (X) (X) := 1.0 - S * (Q_Y * Q_Y + Q_Z * Q_Z); Result (X) (Y) := S * (Q_X * Q_Y - Q_Z * Q_W); Result (X) (Z) := S * (Q_X * Q_Z + Q_Y * Q_W); Result (Y) (X) := S * (Q_X * Q_Y + Q_Z * Q_W); Result (Y) (Y) := 1.0 - S * (Q_X * Q_X + Q_Z * Q_Z); Result (Y) (Z) := S * (Q_Y * Q_Z - Q_X * Q_W); Result (Z) (X) := S * (Q_X * Q_Z - Q_Y * Q_W); Result (Z) (Y) := S * (Q_Y * Q_Z + Q_X * Q_W); Result (Z) (Z) := 1.0 - S * (Q_X * Q_X + Q_Y * Q_Y); return Result; end R; function S (Factors : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := Factors (X); Result (Y) (Y) := Factors (Y); Result (Z) (Z) := Factors (Z); return Result; end S; ---------------------------------------------------------------------------- function FOV (Width, Distance : Element_Type) return Element_Type is (2.0 * EF.Arctan (Width / (2.0 * Distance))); function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Z_Far / (Z_Near - Z_Far); Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far); Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Finite_Perspective; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Element_Type (-1.0); Result (W) (Z) := -Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective; function Infinite_Perspective_Reversed_Z (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [1, 0] instead of [-1 , 1] Result (Z) (Z) := Element_Type (0.0); Result (W) (Z) := Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective_Reversed_Z; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 2.0 / X_Mag; Result (Y) (Y) := 2.0 / Y_Mag; -- Depth normalized to [0, 1] instead of [-1, 1] Result (Z) (Z) := -1.0 / (Z_Far - Z_Near); Result (W) (Z) := -Z_Near / (Z_Far - Z_Near); return Result; end Orthographic; end Orka.Transforms.SIMD_Matrices;
Simplify function R converting a quaternion to a matrix
transforms: Simplify function R converting a quaternion to a matrix Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
8520aca160c476baceb7db826f6e6d836bfe7123
matp/src/mat-consoles.adb
matp/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Formats.Size (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Formats.Size (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; -- ------------------------------ -- Get the field count that was setup through the Print_Title calls. -- ------------------------------ function Get_Field_Count (Console : in Console_Type) return Natural is begin return Console.Field_Count; end Get_Field_Count; end MAT.Consoles;
Implement the Get_Field_Count function
Implement the Get_Field_Count function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3e41f65133898da7af4bd880820109b4744f7224
src/core/util-refs.ads
src/core/util-refs.ads
----------------------------------------------------------------------- -- util-refs -- Reference Counting -- Copyright (C) 2010, 2011, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Concurrent.Counters; -- The <b>Util.Refs</b> package provides support to implement object reference counting. -- -- The data type to share through reference counting has to inherit from <b>Ref_Entity</b> -- and the generic package <b>References</b> has to be instantiated. -- <pre> -- type Data is new Util.Refs.Ref_Entity with record ... end record; -- type Data_Access is access all Data; -- -- package Data_Ref is new Utils.Refs.References (Data, Data_Access); -- </pre> -- -- The reference is used as follows: -- -- <pre> -- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference -- D2 : Data_Ref.Ref := D; -- Share reference -- D.Value.XXXX := 0; -- Set data member XXXX -- </pre> -- -- When a reference is shared in a multi-threaded environment, the reference has to -- be protected by using the <b>References.Atomic_Ref</b> type. -- -- R : Data_Ref.Atomic_Ref; -- -- The reference is then obtained by the protected operation <b>Get</b>. -- -- D : Data_Ref.Ref := R.Get; -- package Util.Refs is pragma Preelaborate; -- Root of referenced objects. type Ref_Entity is abstract tagged limited private; -- Finalize the referenced object. This is called before the object is freed. procedure Finalize (Object : in out Ref_Entity) is null; generic type Element_Type (<>) is new Ref_Entity with private; type Element_Access is access all Element_Type; package Indefinite_References is type Element_Accessor (Element : not null access Element_Type) is limited private with Implicit_Dereference => Element; type Ref is new Ada.Finalization.Controlled with private; -- Create an element and return a reference to that element. function Create (Value : in Element_Access) return Ref; function Value (Object : in Ref'Class) return Element_Accessor with Inline_Always; -- Returns true if the reference does not contain any element. function Is_Null (Object : in Ref'Class) return Boolean with Inline_Always; function "=" (Left, Right : in Ref'Class) return Boolean with Inline_Always; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> generic package Atomic is protected type Atomic_Ref is -- Get the reference function Get return Ref; -- Change the reference procedure Set (Object : in Ref); private Value : Ref; end Atomic_Ref; end Atomic; private type Element_Accessor (Element : not null access Element_Type) is null record; type Ref is new Ada.Finalization.Controlled with record Target : Element_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); end Indefinite_References; generic type Element_Type is new Ref_Entity with private; type Element_Access is access all Element_Type; package References is package IR is new Indefinite_References (Element_Type, Element_Access); subtype Ref is IR.Ref; subtype Element_Accessor is IR.Element_Accessor; -- Create an element and return a reference to that element. function Create return Ref; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> end References; generic type Element_Type is limited private; with procedure Finalize (Object : in out Element_Type) is null; package General_References is type Element_Accessor (Element : not null access Element_Type) is limited private with Implicit_Dereference => Element; type Ref is new Ada.Finalization.Controlled with private; -- Create an element and return a reference to that element. function Create return Ref; function Value (Object : in Ref'Class) return Element_Accessor with Inline_Always; -- Returns true if the reference does not contain any element. function Is_Null (Object : in Ref'Class) return Boolean with Inline_Always; function "=" (Left, Right : in Ref'Class) return Boolean with Inline_Always; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> generic package Atomic is protected type Atomic_Ref is -- Get the reference function Get return Ref; -- Change the reference procedure Set (Object : in Ref); private Value : Ref; end Atomic_Ref; end Atomic; private type Element_Accessor (Element : not null access Element_Type) is null record; type Ref_Data is limited record Ref_Counter : Util.Concurrent.Counters.Counter; Data : aliased Element_Type; end record; type Ref_Data_Access is access all Ref_Data; type Ref is new Ada.Finalization.Controlled with record Target : Ref_Data_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); end General_References; private type Ref_Entity is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; end Util.Refs;
----------------------------------------------------------------------- -- util-refs -- Reference Counting -- Copyright (C) 2010, 2011, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Concurrent.Counters; -- The <b>Util.Refs</b> package provides support to implement object reference counting. -- -- The data type to share through reference counting has to inherit from <b>Ref_Entity</b> -- and the generic package <b>References</b> has to be instantiated. -- <pre> -- type Data is new Util.Refs.Ref_Entity with record ... end record; -- type Data_Access is access all Data; -- -- package Data_Ref is new Utils.Refs.References (Data, Data_Access); -- </pre> -- -- The reference is used as follows: -- -- <pre> -- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference -- D2 : Data_Ref.Ref := D; -- Share reference -- D.Value.XXXX := 0; -- Set data member XXXX -- </pre> -- -- When a reference is shared in a multi-threaded environment, the reference has to -- be protected by using the <b>References.Atomic_Ref</b> type. -- -- R : Data_Ref.Atomic_Ref; -- -- The reference is then obtained by the protected operation <b>Get</b>. -- -- D : Data_Ref.Ref := R.Get; -- package Util.Refs is pragma Preelaborate; -- Root of referenced objects. type Ref_Entity is abstract tagged limited private; -- Finalize the referenced object. This is called before the object is freed. procedure Finalize (Object : in out Ref_Entity) is null; generic type Element_Type (<>) is new Ref_Entity with private; type Element_Access is access all Element_Type; package Indefinite_References is type Element_Accessor (Element : not null access Element_Type) is limited private with Implicit_Dereference => Element; type Ref is new Ada.Finalization.Controlled with private; -- Create an element and return a reference to that element. function Create (Value : in Element_Access) return Ref; function Value (Object : in Ref'Class) return Element_Accessor with Inline; -- Returns true if the reference does not contain any element. function Is_Null (Object : in Ref'Class) return Boolean with Inline_Always; function "=" (Left, Right : in Ref'Class) return Boolean with Inline_Always; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> generic package Atomic is protected type Atomic_Ref is -- Get the reference function Get return Ref; -- Change the reference procedure Set (Object : in Ref); private Value : Ref; end Atomic_Ref; end Atomic; private type Element_Accessor (Element : not null access Element_Type) is null record; type Ref is new Ada.Finalization.Controlled with record Target : Element_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); end Indefinite_References; generic type Element_Type is new Ref_Entity with private; type Element_Access is access all Element_Type; package References is package IR is new Indefinite_References (Element_Type, Element_Access); subtype Ref is IR.Ref; subtype Element_Accessor is IR.Element_Accessor; -- Create an element and return a reference to that element. function Create return Ref; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> end References; generic type Element_Type is limited private; with procedure Finalize (Object : in out Element_Type) is null; package General_References is type Element_Accessor (Element : not null access Element_Type) is limited private with Implicit_Dereference => Element; type Ref is new Ada.Finalization.Controlled with private; -- Create an element and return a reference to that element. function Create return Ref; function Value (Object : in Ref'Class) return Element_Accessor with Inline_Always; -- Returns true if the reference does not contain any element. function Is_Null (Object : in Ref'Class) return Boolean with Inline_Always; function "=" (Left, Right : in Ref'Class) return Boolean with Inline_Always; -- The <b>Atomic_Ref</b> protected type defines a reference to an -- element which can be obtained and changed atomically. The default -- Ada construct: -- -- Ref1 := Ref2; -- -- does not guarantee atomicity of the copy (assignment) and the increment -- of the reference counter (Adjust operation). To replace shared reference -- by another one, the whole assignment and Adjust have to be protected. -- This is achieved by this protected type through the <b>Get</b> and <b>Set</b> generic package Atomic is protected type Atomic_Ref is -- Get the reference function Get return Ref; -- Change the reference procedure Set (Object : in Ref); private Value : Ref; end Atomic_Ref; end Atomic; private type Element_Accessor (Element : not null access Element_Type) is null record; type Ref_Data is limited record Ref_Counter : Util.Concurrent.Counters.Counter; Data : aliased Element_Type; end record; type Ref_Data_Access is access all Ref_Data; type Ref is new Ada.Finalization.Controlled with record Target : Ref_Data_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); end General_References; private type Ref_Entity is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; end Util.Refs;
Remove Inline_Always for the Value since it does not compile with gcc 5 on Ubuntu 16.04
Remove Inline_Always for the Value since it does not compile with gcc 5 on Ubuntu 16.04
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2b9bc6b7192f227ef2e0259b956489c2e6e7faa1
src/asf-servlets-files.adb
src/asf-servlets-files.adb
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; with ASF.Applications; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010, 2011, 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.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; with ASF.Applications; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; Response.Set_Content_Type (Server.Default_Content_Type.all); end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
Use the default content type when the file extension is not recognized
Use the default content type when the file extension is not recognized
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2f7ed2c6a89b16f554074ede5f1588d8d3c0198e
src/security-oauth.ads
src/security-oauth.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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. ----------------------------------------------------------------------- -- == OAuth == -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.2.2. Initial Registry Contents CLIENT_ID : constant String := "client_id"; CLIENT_SECRET : constant String := "client_secret"; RESPONSE_TYPE : constant String := "response_type"; REDIRECT_URI : constant String := "redirect_uri"; SCOPE : constant String := "scope"; STATE : constant String := "state"; CODE : constant String := "code"; ERROR_DESCRIPTION : constant String := "error_description"; ERROR_URI : constant String := "error_uri"; GRANT_TYPE : constant String := "grant_type"; ACCESS_TOKEN : constant String := "access_token"; TOKEN_TYPE : constant String := "token_type"; EXPIRES_IN : constant String := "expires_in"; USERNAME : constant String := "username"; PASSWORD : constant String := "password"; REFRESH_TOKEN : constant String := "refresh_token"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; end Security.OAuth;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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; -- == OAuth == -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.2.2. Initial Registry Contents CLIENT_ID : constant String := "client_id"; CLIENT_SECRET : constant String := "client_secret"; RESPONSE_TYPE : constant String := "response_type"; REDIRECT_URI : constant String := "redirect_uri"; SCOPE : constant String := "scope"; STATE : constant String := "state"; CODE : constant String := "code"; ERROR_DESCRIPTION : constant String := "error_description"; ERROR_URI : constant String := "error_uri"; GRANT_TYPE : constant String := "grant_type"; ACCESS_TOKEN : constant String := "access_token"; TOKEN_TYPE : constant String := "token_type"; EXPIRES_IN : constant String := "expires_in"; USERNAME : constant String := "username"; PASSWORD : constant String := "password"; REFRESH_TOKEN : constant String := "refresh_token"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; private type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth;
Move the declaration of the Application type from OAuth.Clients to the OAuth package so that the definition can be shared between OAuth.Clients and OAuth.Servers
Move the declaration of the Application type from OAuth.Clients to the OAuth package so that the definition can be shared between OAuth.Clients and OAuth.Servers
Ada
apache-2.0
stcarrez/ada-security
3da3739e46e551020891059bccd3bea1b9c744f3
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with DOM.Core; with Gen.Model.Packages; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- ------------------------------ -- Documentation 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); private type Line_Type (Len : Natural) is record Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Lines : Line_Vectors.Vector; end record; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record A : Natural; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with DOM.Core; with Gen.Model.Packages; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; -- ------------------------------ -- Documentation 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); private type Line_Type (Len : Natural) is record Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Lines : Line_Vectors.Vector; end record; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record A : Natural; end record; end Gen.Artifacts.Docs;
Add some special tags that allow to perform specific processing in the documentation
Add some special tags that allow to perform specific processing in the documentation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
07dee8c3a890617f7c24f67fc302f542dc3baac7
src/oto-alc.ads
src/oto-alc.ads
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL, see COPYING file). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Oto.Binary; use Oto; package Oto.ALC is --------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- --------------------------------------------------------------------------- -- Due to the fact that only pointers to device and context are passed -- we ar going to use System.Address for them. subtype Context is System.Address; subtype Device is System.Address; subtype Bool is Binary.Byte; subtype Char is Binary.S_Byte; subtype Double is Long_Float; subtype Enum is Binary.S_Word; subtype Int is Integer; subtype Pointer is System.Address; subtype Short is Binary.S_Short; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UInt is Binary.Word; subtype UShort is Binary.Short; --------------------------------------------------------------------------- ----------------------- -- C O N S T A N T S -- ----------------------- --------------------------------------------------------------------------- -- Bool constants. ALC_FALSE : constant Bool := 0; ALC_TRUE : constant Bool := 1; -- Followed by <Int> Hz ALC_FREQUENCY : constant Enum := 16#1007#; -- Followed by <Int> Hz ALC_REFRESH : constant Enum := 16#1008#; -- Followed by AL_TRUE, AL_FALSE ALC_SYNC : constant Enum := 16#1009#; -- Followed by <Int> Num of requested Mono (3D) Sources ALC_MONO_SOURCES : constant Enum := 16#1010#; -- Followed by <Int> Num of requested Stereo Sources ALC_STEREO_SOURCES : constant Enum := 16#1011#; -- Errors -- No error ALC_NO_ERROR : constant Enum := 0; -- No device ALC_INVALID_DEVICE : constant Enum := 16#A001#; -- Invalid context ID ALC_INVALID_CONTEXT : constant Enum := 16#A002#; -- Bad enum ALC_INVALID_ENUM : constant Enum := 16#A003#; -- Bad value ALC_INVALID_VALUE : constant Enum := 16#A004#; -- Out of memory. ALC_OUT_OF_MEMORY : constant Enum := 16#A005#; -- The Specifier string for default device ALC_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#1004#; ALC_DEVICE_SPECIFIER : constant Enum := 16#1005#; ALC_EXTENSIONS : constant Enum := 16#1006#; ALC_MAJOR_VERSION : constant Enum := 16#1000#; ALC_MINOR_VERSION : constant Enum := 16#1001#; ALC_ATTRIBUTES_SIZE : constant Enum := 16#1002#; ALC_ALL_ATTRIBUTES : constant Enum := 16#1003#; -- Capture extension ALC_EXT_CAPTURE : constant Enum := 1; ALC_CAPTURE_DEVICE_SPECIFIER : constant Enum := 16#310#; ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#311#; ALC_CAPTURE_SAMPLES : constant Enum := 16#312#; -- ALC_ENUMERATE_ALL_EXT enums ALC_ENUMERATE_ALL_EXT : constant Enum := 1; ALC_DEFAULT_ALL_DEVICES_SPECIFIER : constant Enum := 16#1012#; ALC_ALL_DEVICES_SPECIFIER : constant Enum := 16#1013#; --------------------------------------------------------------------------- --------------------------- -- S U B P R O G R A M S -- --------------------------- --------------------------------------------------------------------------- -- Context Management function Create_Context ( ADevice: in Device; Attr_List: in Pointer ) return Context; --ALC_API ALCcontext * ALC_APIENTRY alcCreateContext( ALCdevice *device, const ALCint* attrlist ); function Make_Context_Current (AContext: in Context) return Bool; --ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent( ALCcontext *context ); procedure Process_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcProcessContext( ALCcontext *context ); procedure Suspend_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcSuspendContext( ALCcontext *context ); procedure Destroy_Context (AContext: in Context); --ALC_API void ALC_APIENTRY alcDestroyContext( ALCcontext *context ); function Get_Current_Context return Context; --ALC_API ALCcontext * ALC_APIENTRY alcGetCurrentContext( void ); function Get_Contexts_Device (AContext: in Context) return Device; --ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice( ALCcontext *context ); -- Device Management function Open_Device (Device_Name: in String) return Device; Pragma Inline (Open_Device); function Close_Device (ADevice: in Device) return Bool; -- Error support. -- Obtain the most recent Context error function Get_Error (ADevice: in Device) return Enum; -- Extension support. -- Query for the presence of an extension, and obtain any appropriate -- function pointers and enum values. function Is_Extension_Present ( ADevice: in Device; Ext_Name: in String ) return Bool; Pragma Inline (Is_Extension_Present); function Get_Proc_Address ( ADevice: in Device; Func_Name: in String ) return Pointer; Pragma Inline (Get_Proc_Address); function Get_Enum_Value ( ADevice: in Device; Enum_Name: in String ) return Enum; Pragma Inline (Get_Enum_Value); -- Query functions function Get_String (ADevice: in Device; Param: in Enum) return String; Pragma Inline (Get_String); procedure Get_Integer ( ADevice: in Device; Param: in Enum; Size: in SizeI; Data: in Pointer ); -- Capture functions function Capture_Open_Device ( Device_Name: in String; Frequency: in UInt; Format: in Enum; Buffer_Size: in SizeI ) return Device; Pragma Inline (Capture_Open_Device); function Capture_Close_Device (ADevice: in Device) return Bool; procedure Capture_Start (ADevice: in Device); procedure Capture_Stop (ADevice: in Device); procedure Capture_Samples ( ADevice: in Device; Buffer: in Pointer; Samples: in SizeI ); --------------------------------------------------------------------------- private --------------------------------------------------------------------------- ------------------- -- I M P O R T S -- ------------------- --------------------------------------------------------------------------- Pragma Import (StdCall, Create_Context, "alcCreateContext"); Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent"); Pragma Import (StdCall, Process_Context, "alcProcessContext"); Pragma Import (StdCall, Suspend_Context, "alcSuspendContext"); Pragma Import (StdCall, Destroy_Context, "alcDestroyContext"); Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext"); Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice"); Pragma Import (StdCall, Close_Device, "alcCloseDevice"); Pragma Import (StdCall, Get_Error, "alcGetError"); Pragma Import (StdCall, Get_Integer, "alcGetIntegerv"); Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice"); Pragma Import (StdCall, Capture_Start, "alcCaptureStart"); Pragma Import (StdCall, Capture_Stop, "alcCaptureStop"); Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples"); --------------------------------------------------------------------------- end Oto.ALC;
pragma License (Modified_GPL); ------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: Modified GNU GPLv3 or any later as published by Free Software -- -- Foundation (GMGPL, see COPYING file). -- -- -- -- Copyright © 2014 darkestkhan -- ------------------------------------------------------------------------------ -- This Program is Free Software: You can redistribute it and/or modify -- -- it under the terms of The GNU General Public License as published by -- -- the Free Software Foundation: either version 3 of the license, or -- -- (at your option) any later version. -- -- -- -- This Program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- ------------------------------------------------------------------------------ with System; with Oto.Binary; use Oto; package Oto.ALC is --------------------------------------------------------------------------- --------------- -- T Y P E S -- --------------- --------------------------------------------------------------------------- -- Due to the fact that only pointers to device and context are passed -- we ar going to use System.Address for them. subtype Context is System.Address; subtype Device is System.Address; subtype Bool is Binary.Byte; subtype Char is Binary.S_Byte; subtype Double is Long_Float; subtype Enum is Binary.S_Word; subtype Int is Integer; subtype Pointer is System.Address; subtype Short is Binary.S_Short; subtype SizeI is Integer; subtype UByte is Binary.Byte; subtype UInt is Binary.Word; subtype UShort is Binary.Short; --------------------------------------------------------------------------- ----------------------- -- C O N S T A N T S -- ----------------------- --------------------------------------------------------------------------- -- Bool constants. ALC_FALSE : constant Bool := 0; ALC_TRUE : constant Bool := 1; -- Followed by <Int> Hz ALC_FREQUENCY : constant Enum := 16#1007#; -- Followed by <Int> Hz ALC_REFRESH : constant Enum := 16#1008#; -- Followed by AL_TRUE, AL_FALSE ALC_SYNC : constant Enum := 16#1009#; -- Followed by <Int> Num of requested Mono (3D) Sources ALC_MONO_SOURCES : constant Enum := 16#1010#; -- Followed by <Int> Num of requested Stereo Sources ALC_STEREO_SOURCES : constant Enum := 16#1011#; -- Errors -- No error ALC_NO_ERROR : constant Enum := 0; -- No device ALC_INVALID_DEVICE : constant Enum := 16#A001#; -- Invalid context ID ALC_INVALID_CONTEXT : constant Enum := 16#A002#; -- Bad enum ALC_INVALID_ENUM : constant Enum := 16#A003#; -- Bad value ALC_INVALID_VALUE : constant Enum := 16#A004#; -- Out of memory. ALC_OUT_OF_MEMORY : constant Enum := 16#A005#; -- The Specifier string for default device ALC_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#1004#; ALC_DEVICE_SPECIFIER : constant Enum := 16#1005#; ALC_EXTENSIONS : constant Enum := 16#1006#; ALC_MAJOR_VERSION : constant Enum := 16#1000#; ALC_MINOR_VERSION : constant Enum := 16#1001#; ALC_ATTRIBUTES_SIZE : constant Enum := 16#1002#; ALC_ALL_ATTRIBUTES : constant Enum := 16#1003#; -- Capture extension ALC_EXT_CAPTURE : constant Enum := 1; ALC_CAPTURE_DEVICE_SPECIFIER : constant Enum := 16#310#; ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER : constant Enum := 16#311#; ALC_CAPTURE_SAMPLES : constant Enum := 16#312#; -- ALC_ENUMERATE_ALL_EXT enums ALC_ENUMERATE_ALL_EXT : constant Enum := 1; ALC_DEFAULT_ALL_DEVICES_SPECIFIER : constant Enum := 16#1012#; ALC_ALL_DEVICES_SPECIFIER : constant Enum := 16#1013#; --------------------------------------------------------------------------- --------------------------- -- S U B P R O G R A M S -- --------------------------- --------------------------------------------------------------------------- -- Context Management function Create_Context ( ADevice: in Device; Attr_List: in Pointer ) return Context; function Make_Context_Current (AContext: in Context) return Bool; procedure Process_Context (AContext: in Context); procedure Suspend_Context (AContext: in Context); procedure Destroy_Context (AContext: in Context); function Get_Current_Context return Context; function Get_Contexts_Device (AContext: in Context) return Device; -- Device Management function Open_Device (Device_Name: in String) return Device; Pragma Inline (Open_Device); function Close_Device (ADevice: in Device) return Bool; -- Error support. -- Obtain the most recent Context error function Get_Error (ADevice: in Device) return Enum; -- Extension support. -- Query for the presence of an extension, and obtain any appropriate -- function pointers and enum values. function Is_Extension_Present ( ADevice: in Device; Ext_Name: in String ) return Bool; Pragma Inline (Is_Extension_Present); function Get_Proc_Address ( ADevice: in Device; Func_Name: in String ) return Pointer; Pragma Inline (Get_Proc_Address); function Get_Enum_Value ( ADevice: in Device; Enum_Name: in String ) return Enum; Pragma Inline (Get_Enum_Value); -- Query functions function Get_String (ADevice: in Device; Param: in Enum) return String; Pragma Inline (Get_String); procedure Get_Integer ( ADevice: in Device; Param: in Enum; Size: in SizeI; Data: in Pointer ); -- Capture functions function Capture_Open_Device ( Device_Name: in String; Frequency: in UInt; Format: in Enum; Buffer_Size: in SizeI ) return Device; Pragma Inline (Capture_Open_Device); function Capture_Close_Device (ADevice: in Device) return Bool; procedure Capture_Start (ADevice: in Device); procedure Capture_Stop (ADevice: in Device); procedure Capture_Samples ( ADevice: in Device; Buffer: in Pointer; Samples: in SizeI ); --------------------------------------------------------------------------- private --------------------------------------------------------------------------- ------------------- -- I M P O R T S -- ------------------- --------------------------------------------------------------------------- Pragma Import (StdCall, Create_Context, "alcCreateContext"); Pragma Import (StdCall, Make_Context_Current, "alcMakeContextCurrent"); Pragma Import (StdCall, Process_Context, "alcProcessContext"); Pragma Import (StdCall, Suspend_Context, "alcSuspendContext"); Pragma Import (StdCall, Destroy_Context, "alcDestroyContext"); Pragma Import (StdCall, Get_Current_Context, "alcGetCurrentContext"); Pragma Import (StdCall, Get_Contexts_Device, "alcGetContextsDevice"); Pragma Import (StdCall, Close_Device, "alcCloseDevice"); Pragma Import (StdCall, Get_Error, "alcGetError"); Pragma Import (StdCall, Get_Integer, "alcGetIntegerv"); Pragma Import (StdCall, Capture_Close_Device, "alcCaptureCloseDevice"); Pragma Import (StdCall, Capture_Start, "alcCaptureStart"); Pragma Import (StdCall, Capture_Stop, "alcCaptureStop"); Pragma Import (StdCall, Capture_Samples, "alcCaptureSamples"); --------------------------------------------------------------------------- end Oto.ALC;
Delete C definitions of subprograms.
ALC: Delete C definitions of subprograms. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/oto
65209df96e49604a04830d43ac9b30a7e6480070
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix Get_Facelet_Name to accept view names with the file extension
Fix Get_Facelet_Name to accept view names with the file extension
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
88bfea73f7b5abe61a7908f7357e0113f38c2e25
awa/plugins/awa-counters/src/awa-counters.ads
awa/plugins/awa-counters/src/awa-counters.ads
----------------------------------------------------------------------- -- awa-counters -- -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Schemas; with AWA.Index_Arrays; package AWA.Counters is type Counter_Index_Type is new Natural; package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type); generic Table : ADO.Schemas.Class_Mapping_Access; Field : String; package Definition is function Kind return Counter_Index_Type; end Definition; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); end AWA.Counters;
----------------------------------------------------------------------- -- awa-counters -- -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Schemas; with Util.Strings; with AWA.Index_Arrays; package AWA.Counters is type Counter_Index_Type is new Natural; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); private type Counter_Def is record Table : ADO.Schemas.Class_Mapping_Access; Field : Util.Strings.Name_Access; end record; function "=" (Left, Right : in Counter_Def) return Boolean; function "<" (Left, Right : in Counter_Def) return Boolean; function "&" (Left : in String; Right : in Counter_Def) return String; package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def); end AWA.Counters;
Move the Counter_Arrays package instantiation and the Counter_Def type in the private part
Move the Counter_Arrays package instantiation and the Counter_Def type in the private part
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
149830c38cbe401bd5cba105692145aea10ae3a7
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_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 Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Service : Modules.Wiki_Module_Access := null; Wiki_Space : Wiki_Space_Bean; -- 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 Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; package AWA.Wikis.Beans is type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Service : Modules.Wiki_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 Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Service : Modules.Wiki_Module_Access := null; Wiki_Space : Wiki_Space_Bean; -- 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 Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Declare the Wiki_Admin_Bean
Declare the Wiki_Admin_Bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
757f1872c83257e0fd80ed2627dd631f76ffa1f5
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 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;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2013, 2014, 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.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; Name : in String; 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;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
25ffae47c8fc3c533545d2ebe3aa4238347f95e7
regtests/asf-testsuite.adb
regtests/asf-testsuite.adb
----------------------------------------------------------------------- -- ASF testsuite - Ada Server Faces Test suite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Assertions; with ASF.Contexts.Writer.Tests; with ASF.Views.Facelets.Tests; with ASF.Applications.Views.Tests; with AUnit.Reporter.Text; with AUnit.Run; package body ASF.Testsuite is use AUnit.Assertions; procedure Run is Ret : aliased Test_Suite; function Get_Suite return Access_Test_Suite; function Get_Suite return Access_Test_Suite is begin return Ret'Unchecked_Access; end Get_Suite; procedure Runner is new AUnit.Run.Test_Runner (Get_Suite); Reporter : AUnit.Reporter.Text.Text_Reporter; begin ASF.Contexts.Writer.Tests.Add_Tests (Ret'Unchecked_Access); ASF.Views.Facelets.Tests.Add_Tests (Ret'Unchecked_Access); ASF.Applications.Views.Tests.Add_Tests (Ret'Unchecked_Access); Runner (Reporter); end Run; function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := new Test_Suite; begin ASF.Contexts.Writer.Tests.Add_Tests (Ret); ASF.Views.Facelets.Tests.Add_Tests (Ret); ASF.Applications.Views.Tests.Add_Tests (Ret); return Ret; end Suite; end ASF.Testsuite;
----------------------------------------------------------------------- -- ASF testsuite - Ada Server Faces Test suite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Assertions; with ASF.Contexts.Writer.Tests; with ASF.Views.Facelets.Tests; with ASF.Applications.Views.Tests; with AUnit.Reporter.Text; with AUnit.Run; package body ASF.Testsuite is use AUnit.Assertions; procedure Run is Ret : aliased Test_Suite; function Get_Suite return Access_Test_Suite; function Get_Suite return Access_Test_Suite is begin return Ret'Unchecked_Access; end Get_Suite; procedure Runner is new AUnit.Run.Test_Runner (Get_Suite); Reporter : AUnit.Reporter.Text.Text_Reporter; begin ASF.Contexts.Writer.Tests.Add_Tests (Ret'Unchecked_Access); ASF.Views.Facelets.Tests.Add_Tests (Ret'Unchecked_Access); ASF.Applications.Views.Tests.Add_Tests (Ret'Unchecked_Access); Runner (Reporter); end Run; Tests : aliased Test_Suite; function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := Tests'Access; begin ASF.Contexts.Writer.Tests.Add_Tests (Ret); ASF.Views.Facelets.Tests.Add_Tests (Ret); ASF.Applications.Views.Tests.Add_Tests (Ret); return Ret; end Suite; end ASF.Testsuite;
Use a static tests object to avoid memory leaks
Use a static tests object to avoid memory leaks
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
4e94370045540c79b556138cf9ba6f7eb10352ed
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy defines and implements the set of security rules that specify -- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains -- the security policies. These policies are registered when an application starts, -- before reading the policy configuration files. -- -- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads -- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Returns True if the security controller is defined for the given permission index. function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy defines and implements the set of security rules that specify -- how to protect the system or resources. The <tt>Policy_Manager</tt> maintains -- the security policies. These policies are registered when an application starts, -- before reading the policy configuration files. -- -- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- === Authenticated Permission === -- The `auth-permission` is a pre-defined permission that can be configured in the XML -- configuration. Basically the permission is granted if the security context has a principal. -- Otherwise the permission is denied. The permission is assigned a name and is declared -- as follows: -- -- <policy-rules> -- <auth-permission> -- <name>view-profile</name> -- </auth-permission> -- </policy-rules> -- -- This example defines the `view-profile` permission. -- -- === Grant Permission === -- The `grant-permission` is another pre-defined permission that gives the permission whatever -- the security context. The permission is defined as follows: -- -- <policy-rules> -- <grant-permission> -- <name>anonymous</name> -- </grant-permission> -- </policy-rules> -- -- This example defines the `anonymous` permission. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads --- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Returns True if the security controller is defined for the given permission index. function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Document the grant-permission and auth-permission
Document the grant-permission and auth-permission
Ada
apache-2.0
Letractively/ada-security
1b9f50b858bde251fb010093169dd4d9da1b558e
src/natools-web-simple_pages-multipages.adb
src/natools-web-simple_pages-multipages.adb
------------------------------------------------------------------------------ -- Copyright (c) 2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.Enumeration_IO; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; package body Natools.Web.Simple_Pages.Multipages is package Components is type Enum is (Error, Comment_List, Comment_Path_Prefix, Comment_Path_Suffix, Elements); end Components; package Component_IO is new S_Expressions.Enumeration_IO.Typed_IO (Components.Enum); procedure Build_And_Register (Builder : in out Sites.Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class; Defaults : in Default_Data; Root_Path : in S_Expressions.Atom; Path_Spec : in S_Expressions.Atom); function Key_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom; procedure Update (Defaults : in out Default_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); function Web_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom_Refs.Immutable_Reference; procedure Update_Defaults is new S_Expressions.Interpreter_Loop (Default_Data, Meaningless_Type, Update); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Build_And_Register (Builder : in out Sites.Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class; Defaults : in Default_Data; Root_Path : in S_Expressions.Atom; Path_Spec : in S_Expressions.Atom) is use type S_Expressions.Offset; Name : constant S_Expressions.Atom := (if Path_Spec (Path_Spec'First) in Character'Pos ('+') | Character'Pos ('-') | Character'Pos ('#') then Path_Spec (Path_Spec'First + 1 .. Path_Spec'Last) else Path_Spec); Page : constant Page_Ref := Create (Expression, Defaults.Template, Name); begin declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.File_Path := Defaults.File_Path; Mutator.Web_Path := Web_Path (Root_Path, Path_Spec); end; Register (Page, Builder, Key_Path (Root_Path, Path_Spec)); end Build_And_Register; function Key_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom is use type S_Expressions.Atom; use type S_Expressions.Offset; begin case Spec (Spec'First) is when Character'Pos ('+') => return Path & Spec (Spec'First + 1 .. Spec'Last); when Character'Pos ('-') | Character'Pos ('#') => return S_Expressions.Null_Atom; when others => return Spec; end case; end Key_Path; procedure Update (Defaults : in out Default_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; begin case Component_IO.Value (Name, Components.Error) is when Components.Error => Log (Severities.Error, "Unknown multipage default component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => Set_Comments (Defaults.Template, Arguments); when Components.Comment_Path_Prefix => Set_Comment_Path_Prefix (Defaults.Template, (if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Arguments.Current_Atom else S_Expressions.Null_Atom)); when Components.Comment_Path_Suffix => Set_Comment_Path_Suffix (Defaults.Template, (if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Arguments.Current_Atom else S_Expressions.Null_Atom)); when Components.Elements => Set_Elements (Defaults.Template, Arguments); end case; end Update; function Web_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom_Refs.Immutable_Reference is use type S_Expressions.Atom; use type S_Expressions.Offset; begin case Spec (Spec'First) is when Character'Pos ('+') | Character'Pos ('#') => return S_Expressions.Atom_Ref_Constructors.Create (Path & Spec (Spec'First + 1 .. Spec'Last)); when Character'Pos ('-') => return S_Expressions.Atom_Ref_Constructors.Create (Spec (Spec'First + 1 .. Spec'Last)); when others => return S_Expressions.Atom_Ref_Constructors.Create (Spec); end case; end Web_Path; ---------------------- -- Public Interface -- ---------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is use type S_Expressions.Events.Event; Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (Object.File_Path.Query)); Defaults : Default_Data; Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event := Reader.Current_Event; begin while Event = S_Expressions.Events.Open_List loop Reader.Lock (Lock); Reader.Next (Event); if Event = S_Expressions.Events.Add_Atom then declare Path_Spec : constant S_Expressions.Atom := Reader.Current_Atom; begin if Path_Spec'Length = 0 then Update_Defaults (Reader, Defaults, Meaningless_Value); else Build_And_Register (Builder, Reader, Defaults, Path, Path_Spec); end if; end; end if; Reader.Unlock (Lock); Reader.Next (Event); end loop; end Load; end Natools.Web.Simple_Pages.Multipages;
------------------------------------------------------------------------------ -- Copyright (c) 2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; package body Natools.Web.Simple_Pages.Multipages is procedure Build_And_Register (Builder : in out Sites.Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class; Defaults : in Default_Data; Root_Path : in S_Expressions.Atom; Path_Spec : in S_Expressions.Atom); function Key_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom; function Web_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom_Refs.Immutable_Reference; ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Build_And_Register (Builder : in out Sites.Site_Builder; Expression : in out S_Expressions.Lockable.Descriptor'Class; Defaults : in Default_Data; Root_Path : in S_Expressions.Atom; Path_Spec : in S_Expressions.Atom) is use type S_Expressions.Offset; Name : constant S_Expressions.Atom := (if Path_Spec (Path_Spec'First) in Character'Pos ('+') | Character'Pos ('-') | Character'Pos ('#') then Path_Spec (Path_Spec'First + 1 .. Path_Spec'Last) else Path_Spec); Page : constant Page_Ref := Create (Expression, Defaults.Template, Name); begin declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.File_Path := Defaults.File_Path; Mutator.Web_Path := Web_Path (Root_Path, Path_Spec); end; Register (Page, Builder, Key_Path (Root_Path, Path_Spec)); end Build_And_Register; function Key_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom is use type S_Expressions.Atom; use type S_Expressions.Offset; begin case Spec (Spec'First) is when Character'Pos ('+') => return Path & Spec (Spec'First + 1 .. Spec'Last); when Character'Pos ('-') | Character'Pos ('#') => return S_Expressions.Null_Atom; when others => return Spec; end case; end Key_Path; function Web_Path (Path, Spec : S_Expressions.Atom) return S_Expressions.Atom_Refs.Immutable_Reference is use type S_Expressions.Atom; use type S_Expressions.Offset; begin case Spec (Spec'First) is when Character'Pos ('+') | Character'Pos ('#') => return S_Expressions.Atom_Ref_Constructors.Create (Path & Spec (Spec'First + 1 .. Spec'Last)); when Character'Pos ('-') => return S_Expressions.Atom_Ref_Constructors.Create (Spec (Spec'First + 1 .. Spec'Last)); when others => return S_Expressions.Atom_Ref_Constructors.Create (Spec); end case; end Web_Path; ---------------------- -- Public Interface -- ---------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is use type S_Expressions.Events.Event; Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (Object.File_Path.Query)); Defaults : Default_Data; Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event := Reader.Current_Event; begin while Event = S_Expressions.Events.Open_List loop Reader.Lock (Lock); Reader.Next (Event); if Event = S_Expressions.Events.Add_Atom then declare Path_Spec : constant S_Expressions.Atom := Reader.Current_Atom; begin if Path_Spec'Length = 0 then Update (Defaults.Template, Reader); else Build_And_Register (Builder, Reader, Defaults, Path, Path_Spec); end if; end; end if; Reader.Unlock (Lock); Reader.Next (Event); end loop; end Load; end Natools.Web.Simple_Pages.Multipages;
use the common page template updater
simple_pages-multipages: use the common page template updater
Ada
isc
faelys/natools-web,faelys/natools-web
6e716f49ec36239934ae66ed7415cf77e689e723
src/gen-artifacts-yaml.ads
src/gen-artifacts-yaml.ads
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Yaml database model files -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Packages; package Gen.Artifacts.Yaml is -- ------------------------------ -- Yaml artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with null record; end Gen.Artifacts.Yaml;
----------------------------------------------------------------------- -- gen-artifacts-yaml -- Yaml database model files -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Packages; package Gen.Artifacts.Yaml is -- ------------------------------ -- Yaml artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Read the UML/XMI model file. procedure Read_Model (Handler : in out Artifact; File : in String; Model : in out Gen.Model.Packages.Model_Definition; Context : in out Generator'Class); -- Save the model in a YAML file. procedure Save_Model (Handler : in Artifact; Path : in String; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); private type Artifact is new Gen.Artifacts.Artifact with null record; end Gen.Artifacts.Yaml;
Declare the Save_Model procedure to save the model in YAML file format
Declare the Save_Model procedure to save the model in YAML file format
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
1ba409f52022a7443ff2ad3669bfa370b8cf17eb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "inviter" then return From.Inviter.Get_Value ("name"); else return AWA.Workspaces.Models.Invitation_Ref (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean, Inviter => Bean.Inviter); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key)); end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" then return Util.Beans.Objects.To_Object (Value => From.Members_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; WS : AWA.Workspaces.Models.Workspace_Ref; begin AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS); Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id); Count_Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "inviter" then return From.Inviter.Get_Value ("name"); else return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean, Inviter => Bean.Inviter); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key)); end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" then return Util.Beans.Objects.To_Object (Value => From.Members_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Master_Session := Into.Module.Get_Master_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; WS : AWA.Workspaces.Models.Workspace_Ref; begin AWA.Workspaces.Modules.Get_Workspace (Session, Ctx, WS); Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id); Count_Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "workspace_id", Value => WS.Get_Id); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
Fix the Get_Value operation on the Invitation_Bean
Fix the Get_Value operation on the Invitation_Bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a276ab4e6cffe4e920af3c6f75649d4d3297a8de
src/gen-commands-plugins.adb
src/gen-commands-plugins.adb
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); use GNAT.Command_Line; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then return Name; else return Ada.Strings.Unbounded.To_String (Name_Dir); end if; end Get_Directory_Name; Result_Dir : constant String := Generator.Get_Result_Directory; Name_Dir : Ada.Strings.Unbounded.Unbounded_String; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: d:") is when ASCII.NUL => exit; when 'd' => Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir)); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => Generator.Error ("Cannot create directory {0}", Path); end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] " & "[-d DIR] NAME [ada | web]"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); Put_Line (" The plugin license is controlled by the -l option."); Put_Line (" The plugin type is specified as the last argument which can be one of:"); New_Line; Put_Line (" ada the plugin contains Ada code and a GNAT project is created"); Put_Line (" web the plugin contains XHTML, CSS, Javascript files only"); New_Line; Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME"); Put_Line (" is used by default. The plugin is created in the directory:"); Put_Line (" plugins/NAME or plugins/DIR"); New_Line; Put_Line (" For the Ada plugin, the command generates the following files" & " in the plugin directory:"); Put_Line (" src/<project>-<plugin>.ads"); Put_Line (" src/<project>-<plugin>-<module>.ads"); Put_Line (" src/<project>-<plugin>-<module>.adb"); end Help; end Gen.Commands.Plugins;
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then return Name; else return Ada.Strings.Unbounded.To_String (Name_Dir); end if; end Get_Directory_Name; Result_Dir : constant String := Generator.Get_Result_Directory; Name_Dir : Ada.Strings.Unbounded.Unbounded_String; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: d:") is when ASCII.NUL => exit; when 'd' => Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir)); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Cmd.Usage; return; end if; if Kind /= "ada" and Kind /= "web" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => Generator.Error ("Cannot create directory {0}", Path); end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] " & "[-d DIR] NAME [ada | web]"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); Put_Line (" The plugin license is controlled by the -l option."); Put_Line (" The plugin type is specified as the last argument which can be one of:"); New_Line; Put_Line (" ada the plugin contains Ada code and a GNAT project is created"); Put_Line (" web the plugin contains XHTML, CSS, Javascript files only"); New_Line; Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME"); Put_Line (" is used by default. The plugin is created in the directory:"); Put_Line (" plugins/NAME or plugins/DIR"); New_Line; Put_Line (" For the Ada plugin, the command generates the following files" & " in the plugin directory:"); Put_Line (" src/<project>-<plugin>.ads"); Put_Line (" src/<project>-<plugin>-<module>.ads"); Put_Line (" src/<project>-<plugin>-<module>.adb"); end Help; end Gen.Commands.Plugins;
Use the command usage procedure to report the program usage
Use the command usage procedure to report the program usage
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
bef6fd10b1b8d2744b5349a4d1c3c634e4888f39
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with Security.Permissions; with AWA.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with Security.Permissions; with AWA.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Declare the Load_Page procedures to load a wiki page from its name or an Id
Declare the Load_Page procedures to load a wiki page from its name or an Id
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
72d16892077c2141a4d959316518d7bcf42d09a4
regtests/util-encoders-kdf-tests.adb
regtests/util-encoders-kdf-tests.adb
----------------------------------------------------------------------- -- util-encodes-kdf-tests - Key derivative function tests -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Encoders.SHA1; with Util.Encoders.SHA256; with Util.Encoders.HMAC.SHA1; with Util.Encoders.HMAC.SHA256; with Util.Encoders.Base16; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2; package body Util.Encoders.KDF.Tests is procedure PBKDF2_HMAC_SHA256 is new KDF.PBKDF2 (Length => Util.Encoders.SHA256.HASH_SIZE, Hash => Util.Encoders.HMAC.SHA256.Sign); procedure PBKDF2_HMAC_SHA1 is new KDF.PBKDF2 (Length => Util.Encoders.SHA1.HASH_SIZE, Hash => Util.Encoders.HMAC.SHA1.Sign); package Caller is new Util.Test_Caller (Test, "Encoders.KDF"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA1", Test_PBKDF2_HMAC_SHA1'Access); Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA256", Test_PBKDF2_HMAC_SHA256'Access); end Add_Tests; -- ------------------------------ -- Test derived key generation with HMAC-SHA1. -- ------------------------------ procedure Test_PBKDF2_HMAC_SHA1 (T : in out Test) is Pass : Secret_Key := Create (Password => "password"); Salt : Secret_Key := Create (Password => "salt"); Key : Secret_Key (Length => 20); Hex : Util.Encoders.Base16.Encoder; begin -- RFC6070 - test vector 1 PBKDF2_HMAC_SHA1 (Pass, Salt, 1, Key); Util.Tests.Assert_Equals (T, "0C60C80F961F0E71F3A9B524AF6012062FE037A6", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 1"); -- RFC6070 - test vector 2 PBKDF2_HMAC_SHA1 (Pass, Salt, 2, Key); Util.Tests.Assert_Equals (T, "EA6C014DC72D6F8CCD1ED92ACE1D41F0D8DE8957", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 2"); -- RFC6070 - test vector 3 PBKDF2_HMAC_SHA1 (Pass, Salt, 4096, Key); Util.Tests.Assert_Equals (T, "4B007901B765489ABEAD49D926F721D065A429C1", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 3"); end Test_PBKDF2_HMAC_SHA1; -- ------------------------------ -- Test derived key generation with HMAC-SHA1. -- ------------------------------ procedure Test_PBKDF2_HMAC_SHA256 (T : in out Test) is Pass : Secret_Key := Create (Password => "password"); Salt : Secret_Key := Create (Password => "salt"); Key : Secret_Key (Length => 32); Hex : Util.Encoders.Base16.Encoder; begin -- RFC6070 - test vector 1 PBKDF2_HMAC_SHA256 (Pass, Salt, 1, Key); Util.Tests.Assert_Equals (T, "120FB6CFFCF8B32C43E7225256C4F837A8" & "6548C92CCC35480805987CB70BE17B", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 1"); -- RFC6070 - test vector 2 PBKDF2_HMAC_SHA256 (Pass, Salt, 2, Key); Util.Tests.Assert_Equals (T, "AE4D0C95AF6B46D32D0ADFF928F06DD02A" & "303F8EF3C251DFD6E2D85A95474C43", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 2"); -- RFC6070 - test vector 3 PBKDF2_HMAC_SHA256 (Pass, Salt, 4096, Key); Util.Tests.Assert_Equals (T, "C5E478D59288C841AA530DB6845C4C8D96" & "2893A001CE4E11A4963873AA98134A", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 3"); end Test_PBKDF2_HMAC_SHA256; end Util.Encoders.KDF.Tests;
----------------------------------------------------------------------- -- util-encodes-kdf-tests - Key derivative function tests -- Copyright (C) 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Encoders.SHA1; with Util.Encoders.SHA256; with Util.Encoders.HMAC.SHA1; with Util.Encoders.HMAC.SHA256; with Util.Encoders.Base16; with Util.Encoders.KDF.PBKDF2; package body Util.Encoders.KDF.Tests is procedure PBKDF2_HMAC_SHA256 is new KDF.PBKDF2 (Length => Util.Encoders.SHA256.HASH_SIZE, Hash => Util.Encoders.HMAC.SHA256.Sign); procedure PBKDF2_HMAC_SHA1 is new KDF.PBKDF2 (Length => Util.Encoders.SHA1.HASH_SIZE, Hash => Util.Encoders.HMAC.SHA1.Sign); package Caller is new Util.Test_Caller (Test, "Encoders.KDF"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA1", Test_PBKDF2_HMAC_SHA1'Access); Caller.Add_Test (Suite, "Test Util.Encoders.KDF.PBKDF2.HMAC_SHA256", Test_PBKDF2_HMAC_SHA256'Access); end Add_Tests; -- ------------------------------ -- Test derived key generation with HMAC-SHA1. -- ------------------------------ procedure Test_PBKDF2_HMAC_SHA1 (T : in out Test) is Pass : Secret_Key := Create (Password => "password"); Salt : Secret_Key := Create (Password => "salt"); Key : Secret_Key (Length => 20); Hex : Util.Encoders.Base16.Encoder; begin -- RFC6070 - test vector 1 PBKDF2_HMAC_SHA1 (Pass, Salt, 1, Key); Util.Tests.Assert_Equals (T, "0C60C80F961F0E71F3A9B524AF6012062FE037A6", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 1"); -- RFC6070 - test vector 2 PBKDF2_HMAC_SHA1 (Pass, Salt, 2, Key); Util.Tests.Assert_Equals (T, "EA6C014DC72D6F8CCD1ED92ACE1D41F0D8DE8957", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 2"); -- RFC6070 - test vector 3 PBKDF2_HMAC_SHA1 (Pass, Salt, 4096, Key); Util.Tests.Assert_Equals (T, "4B007901B765489ABEAD49D926F721D065A429C1", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA1 test vector 3"); end Test_PBKDF2_HMAC_SHA1; -- ------------------------------ -- Test derived key generation with HMAC-SHA1. -- ------------------------------ procedure Test_PBKDF2_HMAC_SHA256 (T : in out Test) is Pass : Secret_Key := Create (Password => "password"); Salt : Secret_Key := Create (Password => "salt"); Key : Secret_Key (Length => 32); Hex : Util.Encoders.Base16.Encoder; begin -- RFC6070 - test vector 1 PBKDF2_HMAC_SHA256 (Pass, Salt, 1, Key); Util.Tests.Assert_Equals (T, "120FB6CFFCF8B32C43E7225256C4F837A8" & "6548C92CCC35480805987CB70BE17B", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 1"); -- RFC6070 - test vector 2 PBKDF2_HMAC_SHA256 (Pass, Salt, 2, Key); Util.Tests.Assert_Equals (T, "AE4D0C95AF6B46D32D0ADFF928F06DD02A" & "303F8EF3C251DFD6E2D85A95474C43", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 2"); -- RFC6070 - test vector 3 PBKDF2_HMAC_SHA256 (Pass, Salt, 4096, Key); Util.Tests.Assert_Equals (T, "C5E478D59288C841AA530DB6845C4C8D96" & "2893A001CE4E11A4963873AA98134A", Hex.Transform (Key.Secret), "PBKDF2-HMAC-SHA256 test vector 3"); end Test_PBKDF2_HMAC_SHA256; end Util.Encoders.KDF.Tests;
Remove unecessary with clause
Remove unecessary with clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f83c91377f9a72822af6ed8fb182c1d67dec1c29
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; end record; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; end record; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
Declare the Set_Format procedure and the Doc_Format type
Declare the Set_Format procedure and the Doc_Format type
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
dc9562d148d1906a5f1da7c650f6298d2b6c16b9
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
Add a Print_Footer boolean to the File_Document
Add a Print_Footer boolean to the File_Document
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ea238844139b9b31490f64149fecd8ef6b0b0e43
src/asf-servlets-files.adb
src/asf-servlets-files.adb
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- 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.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter ("web.dir"); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Strings; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; with ASF.Applications; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter (ASF.Applications.VIEW_DIR); Def_Type : constant String := Context.Get_Init_Parameter ("content-type.default"); begin Server.Dir := new String '(Dir); Server.Default_Content_Type := new String '(Def_Type); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Request : in Requests.Request'Class) return Ada.Calendar.Time is pragma Unreferenced (Server, Request); begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Set the content type associated with the given file -- ------------------------------ procedure Set_Content_Type (Server : in File_Servlet; Path : in String; Response : in out Responses.Response'Class) is Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then Response.Set_Content_Type (Server.Default_Content_Type.all); return; end if; if Path (Pos .. Path'Last) = ".css" then Response.Set_Content_Type ("text/css"); return; end if; if Path (Pos .. Path'Last) = ".js" then Response.Set_Content_Type ("text/javascript"); return; end if; if Path (Pos .. Path'Last) = ".html" then Response.Set_Content_Type ("text/html"); return; end if; if Path (Pos .. Path'Last) = ".txt" then Response.Set_Content_Type ("text/plain"); return; end if; if Path (Pos .. Path'Last) = ".png" then Response.Set_Content_Type ("image/png"); return; end if; if Path (Pos .. Path'Last) = ".jpg" then Response.Set_Content_Type ("image/jpg"); return; end if; end Set_Content_Type; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; File_Servlet'Class (Server).Set_Content_Type (Path, Response); declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
Use the ASF.Applications.VIEW_DIR parameter to configure the root directory where static files are stored
Use the ASF.Applications.VIEW_DIR parameter to configure the root directory where static files are stored
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6e70489493463acee82d79828065f831428dfb24
ARM/STM32/driver_demos/demo_adc_polling/src/demo_adc_vbat_polling.adb
ARM/STM32/driver_demos/demo_adc_polling/src/demo_adc_vbat_polling.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This program demonstrates reading the VBat (battery voltage) value from -- an ADC unit, using polling. -- Note that you will likely need to reset the board manually after loading. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with Interfaces; use Interfaces; with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with HAL; use HAL; with STM32.ADC; use STM32.ADC; with STM32.GPIO; use STM32.GPIO; with LCD_Std_Out; use LCD_Std_Out; procedure Demo_ADC_VBat_Polling is Counts : Word; Voltage : Word; -- in millivolts Successful : Boolean; Timed_Out : exception; procedure Print (X, Y : Natural; Value : Word; Suffix : String := ""); ----------- -- Print -- ----------- procedure Print (X, Y : Natural; Value : Word; Suffix : String := "") is Value_Image : constant String := Value'Img; begin Put (X, Y, Value_Image (2 .. Value_Image'Last) & Suffix & " "); end Print; begin Initialize_LEDs; Put_Line ("Starting"); Enable_Clock (VBat.ADC.all); Reset_All_ADC_Units; Configure_Common_Properties (Mode => Independent, Prescalar => PCLK2_Div_2, DMA_Mode => Disabled, Sampling_Delay => Sampling_Delay_5_Cycles); Configure_Unit (VBat.ADC.all, Resolution => ADC_Resolution_12_Bits, Alignment => Right_Aligned); Configure_Regular_Conversions (VBat.ADC.all, Continuous => False, Trigger => Software_Triggered, Enable_EOC => True, Conversions => (1 => (VBat.Channel, Sample_Time => Sample_112_Cycles))); Enable (VBat.ADC.all); loop Start_Conversion (VBat.ADC.all); Poll_For_Status (VBat.ADC.all, Regular_Channel_Conversion_Complete, Successful); if not Successful then raise Timed_Out; end if; Counts := Word (Conversion_Value (VBat.ADC.all)); Print (0, 0, Counts); Voltage := ((Counts * VBat_Bridge_Divisor) * ADC_Supply_Voltage) / 16#FFF#; -- 16#FFF# because we are using 12-bit conversion resolution Print (0, 24, Voltage, "mv"); Toggle (STM32.Board.Green); end loop; end Demo_ADC_VBat_Polling;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This program demonstrates reading the VBat (battery voltage) value from -- an ADC unit, using polling. -- Note that you will likely need to reset the board manually after loading. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with Interfaces; use Interfaces; with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with HAL; use HAL; with STM32.ADC; use STM32.ADC; with STM32.GPIO; use STM32.GPIO; with LCD_Std_Out; use LCD_Std_Out; procedure Demo_ADC_VBat_Polling is Counts : Word; Voltage : Word; -- in millivolts Successful : Boolean; Timed_Out : exception; procedure Print (X, Y : Natural; Value : Word; Suffix : String := ""); ----------- -- Print -- ----------- procedure Print (X, Y : Natural; Value : Word; Suffix : String := "") is Value_Image : constant String := Value'Img; begin Put (X, Y, Value_Image (2 .. Value_Image'Last) & Suffix & " "); end Print; begin Initialize_LEDs; Enable_Clock (VBat.ADC.all); Reset_All_ADC_Units; Configure_Common_Properties (Mode => Independent, Prescalar => PCLK2_Div_2, DMA_Mode => Disabled, Sampling_Delay => Sampling_Delay_5_Cycles); Configure_Unit (VBat.ADC.all, Resolution => ADC_Resolution_12_Bits, Alignment => Right_Aligned); Configure_Regular_Conversions (VBat.ADC.all, Continuous => False, Trigger => Software_Triggered, Enable_EOC => True, Conversions => (1 => (VBat.Channel, Sample_Time => Sample_112_Cycles))); Enable (VBat.ADC.all); loop Start_Conversion (VBat.ADC.all); Poll_For_Status (VBat.ADC.all, Regular_Channel_Conversion_Complete, Successful); if not Successful then raise Timed_Out; end if; Counts := Word (Conversion_Value (VBat.ADC.all)); Print (0, 0, Counts); Voltage := ((Counts * VBat_Bridge_Divisor) * ADC_Supply_Voltage) / 16#FFF#; -- 16#FFF# because we are using 12-bit conversion resolution Print (0, 24, Voltage, "mv"); Toggle (STM32.Board.Green); end loop; end Demo_ADC_VBat_Polling;
remove vestigial Put_Line
remove vestigial Put_Line
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
7b3475a1053d9e9e5062e831c921d9a510879612
regtests/util-files-rolling-tests.ads
regtests/util-files-rolling-tests.ads
----------------------------------------------------------------------- -- util-files-rolling-tests -- Unit tests for rolling file manager -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Rolling.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Format procedure with its pattern replacement. procedure Test_Format (T : in out Test); -- Test a rolling manager configured with ascending rolling mode. procedure Test_Rolling_Ascending (T : in out Test); end Util.Files.Rolling.Tests;
----------------------------------------------------------------------- -- util-files-rolling-tests -- Unit tests for rolling file manager -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Rolling.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Format procedure with its pattern replacement. procedure Test_Format (T : in out Test); -- Test a rolling manager configured with ascending rolling mode. procedure Test_Rolling_Ascending (T : in out Test); -- Test a rolling manager configured with descending rolling mode. procedure Test_Rolling_Descending (T : in out Test); end Util.Files.Rolling.Tests;
Add Test_Rolling_Descending procedure
Add Test_Rolling_Descending procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9df53e633228276b3cbe075f39db51effba04c6f
src/asf-lifecycles-response.adb
src/asf-lifecycles-response.adb
----------------------------------------------------------------------- -- asf-lifecycles-response -- Response phase -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Components.Root; with ASF.Responses; with Util.Log.Loggers; -- The <b>ASF.Lifecycles.Response</b> package defines the behavior -- of the response phase. package body ASF.Lifecycles.Response is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Response"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Response_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Response_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : constant Components.Root.UIViewRoot := Context.Get_View_Root; begin if Components.Root.Get_Root (View) = null then Log.Warn ("Page not found: {0}", Context.Get_View_Name); Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; else Controller.View_Handler.Render_View (Context, View); end if; exception when E : others => Log.Error ("Error when displaying view {0}: {1}: {2}", "?", Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Response;
----------------------------------------------------------------------- -- asf-lifecycles-response -- Response phase -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Components.Root; with ASF.Responses; with Util.Log.Loggers; -- The <b>ASF.Lifecycles.Response</b> package defines the behavior -- of the response phase. package body ASF.Lifecycles.Response is use Ada.Exceptions; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Response"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Response_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Response_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : constant Components.Root.UIViewRoot := Context.Get_View_Root; begin if Components.Root.Get_Root (View) = null then Log.Warn ("Page not found: {0}", Context.Get_View_Name); Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; else Controller.View_Handler.Render_View (Context, View); end if; exception when E : others => Log.Error ("Error when displaying view {0}: {1}: {2}", "?", Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Response;
Remove unused use clauses
Remove unused use clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e1a9329f9c61c102fbecb2d282b65538bde5b8dc
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access); -- Set a policy context information represented by <b>Value</b> and associated with -- the <b>Policy</b>. procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access); -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access; -- Returns True if a context information was registered for the security policy. function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access); -- Set a policy context information represented by <b>Value</b> and associated with -- the <b>Policy</b>. procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access); -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access; -- Returns True if a context information was registered for the security policy. function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
Remove the Permission_Cache record
Remove the Permission_Cache record
Ada
apache-2.0
Letractively/ada-security
73d27328fdf391e3d46a5d8011a505743d002303
awa/src/awa-permissions-services.ads
awa/src/awa-permissions-services.ads
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; with Security.Policies.Roles; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Get the role names that grant the given permission. function Get_Role_Names (Manager : in Permission_Manager; Permission : in Security.Permissions.Permission_Index) return Security.Policies.Roles.Role_Name_Array; -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; -- Delete all the permissions for a user and on the given workspace. procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier); private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access; Roles : Security.Policies.Roles.Role_Policy_Access; end record; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; with Security.Policies.Roles; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Initialize the permissions. procedure Start (Manager : in out Permission_Manager); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Get the role names that grant the given permission. function Get_Role_Names (Manager : in Permission_Manager; Permission : in Security.Permissions.Permission_Index) return Security.Policies.Roles.Role_Name_Array; -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; -- Delete all the permissions for a user and on the given workspace. procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier); private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access; Roles : Security.Policies.Roles.Role_Policy_Access; end record; end AWA.Permissions.Services;
Declare the Start procedure to initialize the permission
Declare the Start procedure to initialize the permission
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7f64677d8c6c4e188aeea160adf74ead0c2d19ff
src/util-serialize-io.adb
src/util-serialize-io.adb
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- 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.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Push the current context when entering in an element. -- ------------------------------ procedure Push (Handler : in out Parser) is use type Util.Serialize.Mappers.Mapper_Access; begin Context_Stack.Push (Handler.Stack); end Push; -- ------------------------------ -- Pop the context and restore the previous context when leaving an element -- ------------------------------ procedure Pop (Handler : in out Parser) is begin Context_Stack.Pop (Handler.Stack); end Pop; function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access is pragma Unreferenced (Handler, Name); begin return null; end Find_Mapper; -- ------------------------------ -- 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 Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); Next : Element_Context_Access; Pos : Positive; begin Log.Debug ("Start object {0}", Name); Context_Stack.Push (Handler.Stack); Next := Context_Stack.Current (Handler.Stack); if Current /= null then Pos := 1; -- Notify we are entering in the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); Child : Mappers.Mapper_Access; begin exit when Node = null; Child := Node.Find_Mapper (Name => Name); if Child = null and then Node.Is_Wildcard then Child := Node; end if; if Child /= null then Log.Debug ("{0} is matching {1}", Name, Child.Get_Name); Child.Start_Object (Handler, Name); Next.Active_Nodes (Pos) := Child; Pos := Pos + 1; end if; end; end loop; while Pos <= Next.Active_Nodes'Last loop Next.Active_Nodes (Pos) := null; Pos := Pos + 1; end loop; else Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name); end if; end Start_Object; -- ------------------------------ -- 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 Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; begin Log.Debug ("Finish object {0}", Name); declare Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin if Current /= null then -- Notify we are leaving the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Finish_Object (Handler, Name); end; end loop; end if; end; Handler.Pop; end Finish_Object; procedure Start_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Push; end Start_Array; procedure Finish_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Pop; end Finish_Array; -- ----------------------- -- 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 Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is use Util.Serialize.Mappers; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin Log.Debug ("Set member {0}", Name); if Current /= null then -- Look each active mapping node. for I in Current.Active_Nodes'Range loop declare Node : constant Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Set_Member (Name => Name, Value => Value, Attribute => Attribute, Context => Handler); exception when E : Util.Serialize.Mappers.Field_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); when E : Util.Serialize.Mappers.Field_Fatal_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); raise; -- For other exception, report an error with the field name and value. when E : others => Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '" & Util.Beans.Objects.To_String (Value) & "': " & Ada.Exceptions.Exception_Message (E)); raise; end; end loop; end if; end Set_Member; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Handler.Mapping_Tree.Add_Mapping (Path, Mapper); end Add_Mapping; -- ------------------------------ -- Dump the mapping tree on the logger using the INFO log level. -- ------------------------------ procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class) is begin Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping "); end Dump; end Util.Serialize.IO;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); procedure Write_Attribute (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream'Class; Name : in String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value)); end Write_Entity; -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Push the current context when entering in an element. -- ------------------------------ procedure Push (Handler : in out Parser) is use type Util.Serialize.Mappers.Mapper_Access; begin Context_Stack.Push (Handler.Stack); end Push; -- ------------------------------ -- Pop the context and restore the previous context when leaving an element -- ------------------------------ procedure Pop (Handler : in out Parser) is begin Context_Stack.Pop (Handler.Stack); end Pop; function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access is pragma Unreferenced (Handler, Name); begin return null; end Find_Mapper; -- ------------------------------ -- 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 Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); Next : Element_Context_Access; Pos : Positive; begin Log.Debug ("Start object {0}", Name); Context_Stack.Push (Handler.Stack); Next := Context_Stack.Current (Handler.Stack); if Current /= null then Pos := 1; -- Notify we are entering in the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); Child : Mappers.Mapper_Access; begin exit when Node = null; Child := Node.Find_Mapper (Name => Name); if Child = null and then Node.Is_Wildcard then Child := Node; end if; if Child /= null then Log.Debug ("{0} is matching {1}", Name, Child.Get_Name); Child.Start_Object (Handler, Name); Next.Active_Nodes (Pos) := Child; Pos := Pos + 1; end if; end; end loop; while Pos <= Next.Active_Nodes'Last loop Next.Active_Nodes (Pos) := null; Pos := Pos + 1; end loop; else Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name); end if; end Start_Object; -- ------------------------------ -- 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 Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; begin Log.Debug ("Finish object {0}", Name); declare Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin if Current /= null then -- Notify we are leaving the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Finish_Object (Handler, Name); end; end loop; end if; end; Handler.Pop; end Finish_Object; procedure Start_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Push; end Start_Array; procedure Finish_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Pop; end Finish_Array; -- ----------------------- -- 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 Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is use Util.Serialize.Mappers; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin Log.Debug ("Set member {0}", Name); if Current /= null then -- Look each active mapping node. for I in Current.Active_Nodes'Range loop declare Node : constant Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Set_Member (Name => Name, Value => Value, Attribute => Attribute, Context => Handler); exception when E : Util.Serialize.Mappers.Field_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); when E : Util.Serialize.Mappers.Field_Fatal_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); raise; -- For other exception, report an error with the field name and value. when E : others => Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '" & Util.Beans.Objects.To_String (Value) & "': " & Ada.Exceptions.Exception_Message (E)); raise; end; end loop; end if; end Set_Member; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Handler.Mapping_Tree.Add_Mapping (Path, Mapper); end Add_Mapping; -- ------------------------------ -- Dump the mapping tree on the logger using the INFO log level. -- ------------------------------ procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class) is begin Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping "); end Dump; end Util.Serialize.IO;
Implement the Write_Attribute and Write_Entity procedures based on Unbounded_String
Implement the Write_Attribute and Write_Entity procedures based on Unbounded_String
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7553573eba03531a930b407ebf63e29ede5d1298
src/wiki-writers-builders.adb
src/wiki-writers-builders.adb
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- 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 Ada.Characters.Conversions; package body Wiki.Writers.Builders is -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Writer_Builder_Type; Content : in Wide_Wide_String) is begin Wide_Wide_Builders.Append (Writer.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Writer_Builder_Type; Content : in Unbounded_Wide_Wide_String) is begin Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content)); end Write; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Writer_Builder_Type; Process : not null access procedure (Chunk : in Wide_Wide_String)) is begin Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Writer_Builder_Type) return String is Pos : Natural := 0; Result : String (1 .. Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wide_Wide_String) is begin for I in Chunk'Range loop Pos := Pos + 1; Result (Pos) := Ada.Characters.Conversions.To_Character (Chunk (I)); end loop; end Convert; begin Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result; end To_String; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ procedure Write (Writer : in out Writer_Builder_Type; Char : in Wide_Wide_Character) is begin Wide_Wide_Builders.Append (Writer.Content, Char); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ procedure Write_Char (Writer : in out Writer_Builder_Type; Char : in Character) is begin Wide_Wide_Builders.Append (Writer.Content, Ada.Characters.Conversions.To_Wide_Wide_Character (Char)); end Write_Char; -- ------------------------------ -- Write the string to the string builder. -- ------------------------------ procedure Write_String (Writer : in out Writer_Builder_Type; Content : in String) is begin for I in Content'Range loop Writer.Write_Char (Content (I)); end loop; end Write_String; type Unicode_Char is mod 2**31; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out Html_Writer_Type'Class; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; end Write_Escape; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_writer_Type'Class) is begin if Stream.Close_Start then Stream.Write_Char ('>'); Stream.Close_Start := False; end if; end Close_Current; procedure Write_Wide_Element (Writer : in out Html_writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Start_Element (Name); Writer.Write_Wide_Text (Content); Writer.End_Element (Name); end Write_Wide_Element; procedure Write_Wide_Attribute (Writer : in out Html_writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is Count : constant Natural := Length (Content); begin if Writer.Close_Start then Writer.Write_Char (' '); Writer.Write_String (Name); Writer.Write_Char ('='); Writer.Write_Char ('"'); for I in 1 .. Count loop declare C : constant Wide_Wide_Character := Element (Content, I); begin if C = '"' then Writer.Write_String ("&quot;"); else Writer.Write_Escape (C); end if; end; end loop; Writer.Write_Char ('"'); end if; end Write_Wide_Attribute; procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Close_Current (Writer); Writer.Write_Char ('<'); Writer.Write_String (Name); Writer.Close_Start := True; end Start_Element; procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Close_Current (Writer); Writer.Write_String ("</"); Writer.Write_String (Name); Writer.Write_Char ('>'); end End_Element; procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is Count : constant Natural := Length (Content); begin Close_Current (Writer); if Count > 0 then for I in 1 .. Count loop Html_Writer_Type'Class (Writer).Write (Element (Content, I)); end loop; end if; end Write_Wide_Text; end Wiki.Writers.Builders;
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- 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 Ada.Characters.Conversions; package body Wiki.Writers.Builders is -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Writer_Builder_Type; Content : in Wide_Wide_String) is begin Wide_Wide_Builders.Append (Writer.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Writer_Builder_Type; Content : in Unbounded_Wide_Wide_String) is begin Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content)); end Write; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Writer_Builder_Type; Process : not null access procedure (Chunk : in Wide_Wide_String)) is begin Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Writer_Builder_Type) return String is Pos : Natural := 0; Result : String (1 .. Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wide_Wide_String) is begin for I in Chunk'Range loop Pos := Pos + 1; Result (Pos) := Ada.Characters.Conversions.To_Character (Chunk (I)); end loop; end Convert; begin Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result; end To_String; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ procedure Write (Writer : in out Writer_Builder_Type; Char : in Wide_Wide_Character) is begin Wide_Wide_Builders.Append (Writer.Content, Char); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ procedure Write_Char (Writer : in out Writer_Builder_Type; Char : in Character) is begin Wide_Wide_Builders.Append (Writer.Content, Ada.Characters.Conversions.To_Wide_Wide_Character (Char)); end Write_Char; -- ------------------------------ -- Write the string to the string builder. -- ------------------------------ procedure Write_String (Writer : in out Writer_Builder_Type; Content : in String) is begin for I in Content'Range loop Writer.Write_Char (Content (I)); end loop; end Write_String; type Unicode_Char is mod 2**31; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out Html_Writer_Type'Class; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; end Write_Escape; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_writer_Type'Class) is begin if Stream.Close_Start then Stream.Write_Char ('>'); Stream.Close_Start := False; end if; end Close_Current; procedure Write_Wide_Element (Writer : in out Html_writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Start_Element (Name); Writer.Write_Wide_Text (Content); Writer.End_Element (Name); end Write_Wide_Element; procedure Write_Wide_Attribute (Writer : in out Html_writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is Count : constant Natural := Length (Content); begin if Writer.Close_Start then Writer.Write_Char (' '); Writer.Write_String (Name); Writer.Write_Char ('='); Writer.Write_Char ('"'); for I in 1 .. Count loop declare C : constant Wide_Wide_Character := Element (Content, I); begin if C = '"' then Writer.Write_String ("&quot;"); else Writer.Write_Escape (C); end if; end; end loop; Writer.Write_Char ('"'); end if; end Write_Wide_Attribute; procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Close_Current (Writer); Writer.Write_Char ('<'); Writer.Write_String (Name); Writer.Close_Start := True; end Start_Element; procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Close_Current (Writer); Writer.Write_String ("</"); Writer.Write_String (Name); Writer.Write_Char ('>'); end End_Element; procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is Count : constant Natural := Length (Content); begin Close_Current (Writer); if Count > 0 then for I in 1 .. Count loop Html_Writer_Type'Class (Writer).Write_Escape (Element (Content, I)); end loop; end if; end Write_Wide_Text; end Wiki.Writers.Builders;
Use Write_Escape to escape the characters
Use Write_Escape to escape the characters
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
95dd80b224d27f22ca37cfeb8fc54305bad43190
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- 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 Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) 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 Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.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; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.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 procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); 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); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; 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 : Wiki.Strings.WChar; 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 C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := not P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := P.Context.Is_Included; end if; else End_Element (P, Tag); end if; 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; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := not P.Context.Is_Included; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); 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); Add_Element (Name); 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 Wiki.Strings.WChar) 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 : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (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; if Len > 0 and then Name (Name'First) = '#' and then Name (Name'First + 1) >= '0' and then Name (Name'First + 1) <= '9' then begin C := Wiki.Strings.WChar'Val (Natural'Value (Name (Name'First + 1 .. Len))); Parse_Text (P, C); return; exception when Constraint_Error => null; end; end if; -- 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, Wiki.Strings.To_WChar (Name (I))); end loop; if Len > 0 and then Len < Name'Last and then C = ';' then Parse_Text (P, ';'); end if; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- 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 Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) 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 Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.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; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.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 procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); 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); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; 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 : Wiki.Strings.WChar; 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 C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := not P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := P.Context.Is_Included; end if; else End_Element (P, Tag); end if; 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; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := not P.Context.Is_Included; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); 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); Add_Element (Name); end Parse_Element; use Interfaces; function From_Hex (C : in Character) return Interfaces.Unsigned_8 is (if C >= '0' and C <= '9' then Character'Pos (C) - Character'Pos ('0') elsif C >= 'A' and C <= 'F' then Character'Pos (C) - Character'Pos ('A') + 10 elsif C >= 'a' and C <= 'f' then Character'Pos (C) - Character'Pos ('a') + 10 else raise Constraint_Error); function From_Hex (Value : in String) return Wiki.Strings.WChar is Result : Interfaces.Unsigned_32 := 0; begin for C of Value loop Result := Interfaces.Shift_Left (Result, 4); Result := Result + Interfaces.Unsigned_32 (From_Hex (C)); end loop; return Wiki.Strings.WChar'Val (Result); end From_Hex; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) 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 : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (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; if Len > 0 and then Name (Name'First) = '#' then if Name (Name'First + 1) >= '0' and then Name (Name'First + 1) <= '9' then begin C := Wiki.Strings.WChar'Val (Natural'Value (Name (Name'First + 1 .. Len))); Parse_Text (P, C); return; exception when Constraint_Error => null; end; elsif Name (Name'First + 1) = 'x' then begin C := From_Hex (Name (Name'First + 2 .. Len)); Parse_Text (P, C); return; exception when Constraint_Error => null; end; end if; end if; -- 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, Wiki.Strings.To_WChar (Name (I))); end loop; if Len > 0 and then Len < Name'Last and then C = ';' then Parse_Text (P, ';'); end if; end Parse_Entity; end Wiki.Parsers.Html;
Add support to parse HTML entities in the hexadecimal form: &#xHHHH;
Add support to parse HTML entities in the hexadecimal form: &#xHHHH;
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f274753938c4074eb518ca058e9c5668353de242
src/util-log-appenders.adb
src/util-log-appenders.adb
----------------------------------------------------------------------- -- Appenders -- Log appenders -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Formatting; with Ada.Strings; with Ada.Strings.Fixed; with Util.Strings.Transforms; with Util.Log.Loggers; with Util.Properties.Basic; package body Util.Log.Appenders is use Ada; -- ------------------------------ -- Get the log level that triggers display of the log events -- ------------------------------ function Get_Level (Self : in Appender) return Level_Type is begin return Self.Level; end Get_Level; -- ------------------------------ -- Set the log level. -- ------------------------------ procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type) is Prop_Name : constant String := Name & ".level"; begin if Properties.Exists (Prop_Name) then Self.Level := Get_Level (Properties.Get (Prop_Name), Level); else Self.Level := Level; end if; end Set_Level; -- ------------------------------ -- Set the log layout format. -- ------------------------------ procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type) is use Ada.Strings; use Util.Strings.Transforms; Prop_Name : constant String := Name & ".layout"; begin if Properties.Exists (Prop_Name) then declare Value : constant String := To_Lower_Case (Fixed.Trim (Properties.Get (Prop_Name), Both)); begin if Value = "message" then Self.Layout := MESSAGE; elsif Value = "level-message" then Self.Layout := LEVEL_MESSAGE; elsif Value = "date-level-message" or Value = "level-date-message" then Self.Layout := DATE_LEVEL_MESSAGE; else Self.Layout := FULL; end if; end; else Self.Layout := Layout; end if; end Set_Layout; -- ------------------------------ -- Format the event into a string -- ------------------------------ function Format (Self : in Appender; Event : in Log_Event) return String is begin case Self.Layout is when MESSAGE => return To_String (Event.Message); when LEVEL_MESSAGE => return Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when DATE_LEVEL_MESSAGE => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when FULL => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & " - " & Loggers.Get_Logger_Name (Event.Logger.all) & " - " & To_String (Event.Message); end case; end Format; procedure Append (Self : in out File_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Self.Output, Format (Self, Event)); if Self.Immediate_Flush then Self.Flush; end if; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is begin Text_IO.Flush (Self.Output); end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.Flush; Text_IO.Close (File => Self.Output); end Finalize; -- ------------------------------ -- Create a file appender and configure it according to the properties -- ------------------------------ function Create_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is use Util.Properties.Basic; Path : constant String := Properties.Get (Name & ".File"); Append : constant Boolean := Boolean_Property.Get (Properties, Name & ".append", True); Result : constant File_Appender_Access := new File_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Set_File (Path, Append); Result.Immediate_Flush := Boolean_Property.Get (Properties, Name & ".immediateFlush", True); return Result.all'Access; end Create_File_Appender; -- ------------------------------ -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. -- ------------------------------ procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True) is Mode : Text_IO.File_Mode; begin if Append then Mode := Text_IO.Append_File; else Mode := Text_IO.Out_File; end if; Text_IO.Open (File => Self.Output, Name => Path, Mode => Mode); exception when Text_IO.Name_Error => Text_IO.Create (File => Self.Output, Name => Path); end Set_File; procedure Append (Self : in out Console_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Format (Self, Event)); end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out Console_Appender) is pragma Unreferenced (Self); begin Text_IO.Flush; end Flush; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Append (Event); end loop; end Append; -- ------------------------------ -- Create a console appender and configure it according to the properties -- ------------------------------ function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is Result : constant Console_Appender_Access := new Console_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); return Result.all'Access; end Create_Console_Appender; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out List_Appender) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Flush; end loop; end Flush; -- ------------------------------ -- Add the appender to the list. -- ------------------------------ procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access) is begin if Self.Count < Self.Appenders'Last then Self.Count := Self.Count + 1; Self.Appenders (Self.Count) := Object; end if; end Add_Appender; -- ------------------------------ -- Create a list appender and configure it according to the properties -- ------------------------------ function Create_List_Appender return List_Appender_Access is Result : constant List_Appender_Access := new List_Appender; begin return Result; end Create_List_Appender; end Util.Log.Appenders;
----------------------------------------------------------------------- -- util-log-appenders -- Log appenders -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Formatting; with Ada.Strings; with Ada.Strings.Fixed; with Util.Strings.Transforms; with Util.Log.Loggers; with Util.Properties.Basic; package body Util.Log.Appenders is use Ada; -- ------------------------------ -- Get the log level that triggers display of the log events -- ------------------------------ function Get_Level (Self : in Appender) return Level_Type is begin return Self.Level; end Get_Level; -- ------------------------------ -- Set the log level. -- ------------------------------ procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type) is Prop_Name : constant String := Name & ".level"; begin if Properties.Exists (Prop_Name) then Self.Level := Get_Level (Properties.Get (Prop_Name), Level); else Self.Level := Level; end if; end Set_Level; -- ------------------------------ -- Set the log layout format. -- ------------------------------ procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type) is use Ada.Strings; use Util.Strings.Transforms; Prop_Name : constant String := Name & ".layout"; begin if Properties.Exists (Prop_Name) then declare Value : constant String := To_Lower_Case (Fixed.Trim (Properties.Get (Prop_Name), Both)); begin if Value = "message" then Self.Layout := MESSAGE; elsif Value = "level-message" then Self.Layout := LEVEL_MESSAGE; elsif Value = "date-level-message" or Value = "level-date-message" then Self.Layout := DATE_LEVEL_MESSAGE; else Self.Layout := FULL; end if; end; else Self.Layout := Layout; end if; end Set_Layout; -- ------------------------------ -- Format the event into a string -- ------------------------------ function Format (Self : in Appender; Event : in Log_Event) return String is begin case Self.Layout is when MESSAGE => return To_String (Event.Message); when LEVEL_MESSAGE => return Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when DATE_LEVEL_MESSAGE => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & ": " & To_String (Event.Message); when FULL => return "[" & Calendar.Formatting.Image (Event.Time) & "] " & Get_Level_Name (Event.Level) & " - " & Loggers.Get_Logger_Name (Event.Logger.all) & " - " & To_String (Event.Message); end case; end Format; procedure Append (Self : in out File_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Self.Output, Format (Self, Event)); if Self.Immediate_Flush then Self.Flush; end if; end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out File_Appender) is begin Text_IO.Flush (Self.Output); end Flush; -- ------------------------------ -- Flush and close the file. -- ------------------------------ overriding procedure Finalize (Self : in out File_Appender) is begin Self.Flush; Text_IO.Close (File => Self.Output); end Finalize; -- ------------------------------ -- Create a file appender and configure it according to the properties -- ------------------------------ function Create_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is use Util.Properties.Basic; Path : constant String := Properties.Get (Name & ".File"); Append : constant Boolean := Boolean_Property.Get (Properties, Name & ".append", True); Result : constant File_Appender_Access := new File_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); Result.Set_File (Path, Append); Result.Immediate_Flush := Boolean_Property.Get (Properties, Name & ".immediateFlush", True); return Result.all'Access; end Create_File_Appender; -- ------------------------------ -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. -- ------------------------------ procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True) is Mode : Text_IO.File_Mode; begin if Append then Mode := Text_IO.Append_File; else Mode := Text_IO.Out_File; end if; Text_IO.Open (File => Self.Output, Name => Path, Mode => Mode); exception when Text_IO.Name_Error => Text_IO.Create (File => Self.Output, Name => Path); end Set_File; procedure Append (Self : in out Console_Appender; Event : in Log_Event) is begin if Self.Level >= Event.Level then Text_IO.Put_Line (Format (Self, Event)); end if; end Append; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out Console_Appender) is pragma Unreferenced (Self); begin Text_IO.Flush; end Flush; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Append (Event); end loop; end Append; -- ------------------------------ -- Create a console appender and configure it according to the properties -- ------------------------------ function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access is Result : constant Console_Appender_Access := new Console_Appender; begin Result.Set_Level (Name, Properties, Default); Result.Set_Layout (Name, Properties, FULL); return Result.all'Access; end Create_Console_Appender; -- ------------------------------ -- Flush the log events. -- ------------------------------ overriding procedure Flush (Self : in out List_Appender) is begin for I in 1 .. Self.Count loop Self.Appenders (I).Flush; end loop; end Flush; -- ------------------------------ -- Add the appender to the list. -- ------------------------------ procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access) is begin if Self.Count < Self.Appenders'Last then Self.Count := Self.Count + 1; Self.Appenders (Self.Count) := Object; end if; end Add_Appender; -- ------------------------------ -- Create a list appender and configure it according to the properties -- ------------------------------ function Create_List_Appender return List_Appender_Access is Result : constant List_Appender_Access := new List_Appender; begin return Result; end Create_List_Appender; end Util.Log.Appenders;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b0e2e8b68e841194beb7b4a19471532d11dd5e7b
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ado-sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise Session_Error; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Get the audit manager. -- ------------------------------ function Get_Audit_Manager (Database : in Master_Session) return access Audits.Audit_Manager'Class is begin return Database.Audit; end Get_Audit_Manager; -- ------------------------------ -- Internal operation to get access to the database connection. -- ------------------------------ procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)) is begin Check_Session (Database); Process (Database.Impl.Database.Value.all); end Access_Connection; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ado-sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise Session_Error; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Get the audit manager. -- ------------------------------ function Get_Audit_Manager (Database : in Master_Session) return access Audits.Audit_Manager'Class is begin return Database.Audit; end Get_Audit_Manager; -- ------------------------------ -- Internal operation to get access to the database connection. -- ------------------------------ procedure Access_Connection (Database : in out Master_Session; Process : not null access procedure (Connection : in out Database_Connection'Class)) is begin Check_Session (Database); Process (Database.Impl.Database.Value); end Access_Connection; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Update to use Implicit_Deference support in Util.Refs
Update to use Implicit_Deference support in Util.Refs
Ada
apache-2.0
stcarrez/ada-ado
132f7def1c03a2a07917f2b38b241db0c3eaf014
src/gen-artifacts-distribs-copies.adb
src/gen-artifacts-distribs-copies.adb
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- 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.Directories; with Util.Log.Loggers; -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. package body Gen.Artifacts.Distribs.Copies is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Copies"); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is pragma Unreferenced (Node); Result : constant Copy_Rule_Access := new Copy_Rule; begin return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Copy_Rule) return String is pragma Unreferenced (Rule); begin return "copy"; end Get_Install_Name; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is pragma Unreferenced (Rule, Context); Source : constant String := Get_First_Path (Files); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Log.Info ("copy {0} to {1}", Source, Path); Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Source, Target_Name => Path, Form => "preserve=all_attributes, mode=overwrite"); end Install; end Gen.Artifacts.Distribs.Copies;
----------------------------------------------------------------------- -- gen-artifacts-distribs-copies -- Copy based distribution artifact -- 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.Directories; with Util.Log.Loggers; -- The <b>Gen.Artifacts.Distribs.Copies</b> package provides distribution rules -- to copy a file or a directory to the distribution area. package body Gen.Artifacts.Distribs.Copies is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Copies"); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node; Copy_First_File : in Boolean) return Distrib_Rule_Access is pragma Unreferenced (Node); Result : constant Copy_Rule_Access := new Copy_Rule; begin Result.Copy_First_File := Copy_First_File; return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Copy_Rule) return String is pragma Unreferenced (Rule); begin return "copy"; end Get_Install_Name; overriding procedure Install (Rule : in Copy_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is pragma Unreferenced (Context); use type Ada.Containers.Count_Type; Source : constant String := Get_Source_Path (Files, Rule.Copy_First_File); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if Files.Length > 1 then Log.Info ("copy {0} to {1} (ignoring {2} files)", Source, Path, Natural'Image (Natural (Files.Length) - 1)); else Log.Info ("copy {0} to {1}", Source, Path); end if; Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Source, Target_Name => Path, Form => "preserve=all_attributes, mode=overwrite"); end Install; end Gen.Artifacts.Distribs.Copies;
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Add a copy-first command to copy the first file found only (the default is to copy the last one since this is the reverse search path)
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
bb1e28437db05f19e936a486d44d42f98800cd17
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Systems.Os; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; function Get_Test_Library return String; function Get_Test_Symbol return String; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; function Get_Test_Library return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "libcrypto.so"; else return "libz.dll"; end if; end Get_Test_Library; function Get_Test_Symbol return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "inflate"; else return "compress"; end if; end Get_Test_Symbol; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); Sym := Util.Systems.DLLs.Get_Symbol (Lib, Get_Test_Symbol); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Systems.Os; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; function Get_Test_Library return String; function Get_Test_Symbol return String; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; function Get_Test_Library return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "libcrypto.so"; else return "libz.dll"; end if; end Get_Test_Library; function Get_Test_Symbol return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "EVP_sha"; else return "compress"; end if; end Get_Test_Symbol; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); Sym := Util.Systems.DLLs.Get_Symbol (Lib, Get_Test_Symbol); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Change the symbol name to use a symbol that hopefully exists in almost all installation of libcrypto on Unix
Change the symbol name to use a symbol that hopefully exists in almost all installation of libcrypto on Unix
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
50b20666b37f010cba4b7b1fd35b248dbf711d8a
src/util-events.ads
src/util-events.ads
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 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.Calendar; package Util.Events is type Event is tagged private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; private type Event is tagged record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 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.Calendar; package Util.Events is type Event is tagged private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; type Event_Listener is limited interface; private type Event is tagged record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
Declare the Event_Listener interface
Declare the Event_Listener interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bba37615aa29471c72606b547dbcc2b7b055215a
src/mysql/ado-schemas-mysql.adb
src/mysql/ado-schemas-mysql.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "decimal" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First < 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value , ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Col.Size := String_To_Length (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Value := Stmt.Get_Unbounded_String (4); Col.Is_Primary := Value = "PRI"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Mysql;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "decimal" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First = 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value, ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Col.Size := String_To_Length (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Value := Stmt.Get_Unbounded_String (4); Col.Is_Primary := Value = "PRI"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Mysql;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-ado
4fddbd0e09e151a08dbee553bb3d5b108697401e
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- 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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured -- on the wiki engine. The document reader operations are invoked while parsing the wiki -- text. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Into : in Wiki.Documents.Document_Reader_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax_Type; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- 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 Wide_Wide_Character); -- 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 Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- 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 Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured -- on the wiki engine. The document reader operations are invoked while parsing the wiki -- text. procedure Parse (Engine : in out Parser; Text : in Wide_Wide_String; Into : in Wiki.Documents.Document_Reader_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is tagged limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Syntax : Wiki_Syntax_Type; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Wiki.Strings.BString; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; 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; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- 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 Wide_Wide_Character); -- 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 Wide_Wide_Character); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wide_Wide_String) return Boolean; procedure Start_Element (P : in out Parser; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
Use Wiki.Strings.BString to collect text
Use Wiki.Strings.BString to collect text
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b334573c079330f5f6d14e1a54753d31ab5c4266
matp/src/mat-consoles.ads
matp/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_LEVEL, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_NEXT, F_PREVIOUS, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, 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); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; 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_LEVEL, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_START_TIME, F_END_TIME, F_MALLOC_COUNT, F_REALLOC_COUNT, F_FREE_COUNT, F_EVENT_RANGE, F_ID, F_OLD_ADDR, F_GROW_SIZE, F_TIME, F_DURATION, F_EVENT, F_NEXT, F_PREVIOUS, F_MODE, F_FRAME_ID, F_RANGE_ADDR, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_INFO, N_EVENT_ID, 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); -- Get the field count that was setup through the Print_Title calls. function Get_Field_Count (Console : in Console_Type) return Natural; -- Reset the field count. procedure Clear_Fields (Console : in out Console_Type); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_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 Clear_Fields procedure
Declare Clear_Fields procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
714c025a4d3f125ac3e219040e7d21c9a484dfe3
src/gen-model-packages.adb
src/gen-model-packages.adb
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query 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 Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Enums; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Beans; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "enums" then return From.Enums_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "beans" then return From.Beans_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given enum in the model. -- ------------------------------ procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class) is Name : constant String := Enum.Get_Name; begin Log.Info ("Registering enum {0}", Name); O.Register_Package (Enum.Pkg_Name, Enum.Package_Def); if Enum.Package_Def.Enums.Find (Name) /= null then raise Name_Exist with "Enum '" & Name & "' already defined"; end if; Enum.Package_Def.Enums.Append (Enum.all'Access); O.Enums.Append (Enum.all'Access); Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access, Gen.Model.Mappings.T_ENUM); end Register_Enum; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is Name : constant String := Table.Get_Name; begin Log.Info ("Registering table {0}", Name); O.Register_Package (Table.Pkg_Name, Table.Package_Def); if Table.Package_Def.Tables.Find (Name) /= null then raise Name_Exist with "Table '" & Name & "' already defined"; end if; Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register the declaration of the given bean in the model. -- ------------------------------ procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class) is begin O.Register_Package (Bean.Pkg_Name, Bean.Package_Def); Bean.Package_Def.Beans.Append (Bean.all'Access); O.Queries.Append (Bean.all'Access); end Register_Bean; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Definition_Access := Table_List.Element (Table_Iter); begin if Table.all in Table_Definition'Class then Prepare_Table (Table_Definition_Access (Table)); else Table.Prepare; end if; end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin Log.Info ("Preparing package {0}", O.Pkg_Name); O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; O.Enums.Sort; O.Queries.Sort; Prepare_Tables (O.Enums); Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC); O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Beans_Bean := Util.Beans.Objects.To_Object (O.Beans'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; O.Tables.Sort; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query 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 Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Enums; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Beans; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "enums" then return From.Enums_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "beans" then return From.Beans_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given enum in the model. -- ------------------------------ procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class) is Name : constant String := Enum.Get_Name; begin Log.Info ("Registering enum {0}", Name); O.Register_Package (Enum.Pkg_Name, Enum.Package_Def); if Enum.Package_Def.Enums.Find (Name) /= null then raise Name_Exist with "Enum '" & Name & "' already defined"; end if; Enum.Package_Def.Enums.Append (Enum.all'Access); O.Enums.Append (Enum.all'Access); Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access, Gen.Model.Mappings.T_ENUM); end Register_Enum; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is Name : constant String := Table.Get_Name; begin Log.Info ("Registering table {0}", Name); O.Register_Package (Table.Pkg_Name, Table.Package_Def); if Table.Package_Def.Tables.Find (Name) /= null then raise Name_Exist with "Table '" & Name & "' already defined"; end if; Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register the declaration of the given bean in the model. -- ------------------------------ procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class) is begin O.Register_Package (Bean.Pkg_Name, Bean.Package_Def); Bean.Package_Def.Beans.Append (Bean.all'Access); O.Queries.Append (Bean.all'Access); end Register_Bean; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Definition_Access := Table_List.Element (Table_Iter); begin if Table.all in Table_Definition'Class then Prepare_Table (Table_Definition_Access (Table)); else Table.Prepare; end if; end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin Log.Info ("Preparing package {0}", O.Pkg_Name); O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; O.Enums.Sort; O.Queries.Sort; Prepare_Tables (O.Enums); Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); Prepare_Tables (O.Beans); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC); O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Beans_Bean := Util.Beans.Objects.To_Object (O.Beans'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; O.Tables.Sort; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
Prepare the Ada beans by invoking the Prepare operation on each of them
Prepare the Ada beans by invoking the Prepare operation on each of them
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
8cf8040f95558347affa77ba9b31313a4cd12f21
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- 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.Measures; with Util.Test_Caller; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with AWA.Counters.Definition; with Security.Contexts; package body AWA.Counters.Modules.Tests is package User_Counter is new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE, "count"); package Session_Counter is new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE, "count"); package Caller is new Util.Test_Caller (Test, "Counters.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment", Test_Increment'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Increment (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]"); AWA.Counters.Increment (User_Counter.Index, Context.Get_User); T.Manager := AWA.Counters.Modules.Get_Counter_Module; T.Assert (T.Manager /= null, "There is no counter plugin"); T.Manager.Flush; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop AWA.Counters.Increment (User_Counter.Index, Context.Get_User); end loop; Util.Measures.Report (S, "AWA.Counters.Increment", 1000); end; declare S : Util.Measures.Stamp; begin T.Manager.Flush; Util.Measures.Report (S, "AWA.Counters.Flush"); end; -- T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; -- T.Assert (T.Manager /= null, "There is no wiki manager"); -- -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- T.Assert (W.Is_Inserted, "The new wiki space was not created"); -- -- W.Set_Name ("Test wiki space update"); -- W.Set_Is_Public (True); -- T.Manager.Save_Wiki_Space (W); -- -- T.Manager.Load_Wiki_Space (Wiki => W2, -- Id => W.Get_Id); -- Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), -- "Invalid wiki space name"); end Test_Increment; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (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]"); -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- -- P.Set_Name ("The page"); -- P.Set_Title ("The page title"); -- T.Manager.Create_Wiki_Page (W, P, C); -- T.Assert (P.Is_Inserted, "The new wiki page was not created"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (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]"); -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- -- P.Set_Name ("The page"); -- P.Set_Title ("The page title"); -- T.Manager.Create_Wiki_Page (W, P, C); -- -- C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); -- C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); -- C.Set_Save_Comment ("A first version"); -- T.Manager.Create_Wiki_Content (P, C); -- T.Assert (C.Is_Inserted, "The new wiki content was not created"); -- T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); -- T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; end AWA.Counters.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- 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.Measures; with Util.Test_Caller; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with AWA.Counters.Definition; with AWA.Users.Models; with Security.Contexts; package body AWA.Counters.Modules.Tests is package User_Counter is new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE, "count"); package Session_Counter is new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE, "count"); package Caller is new Util.Test_Caller (Test, "Counters.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment", Test_Increment'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Increment (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]"); AWA.Counters.Increment (User_Counter.Index, Context.Get_User); T.Manager := AWA.Counters.Modules.Get_Counter_Module; T.Assert (T.Manager /= null, "There is no counter plugin"); T.Manager.Flush; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop AWA.Counters.Increment (User_Counter.Index, Context.Get_User); end loop; Util.Measures.Report (S, "AWA.Counters.Increment", 1000); end; declare S : Util.Measures.Stamp; begin T.Manager.Flush; Util.Measures.Report (S, "AWA.Counters.Flush"); end; -- T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; -- T.Assert (T.Manager /= null, "There is no wiki manager"); -- -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- T.Assert (W.Is_Inserted, "The new wiki space was not created"); -- -- W.Set_Name ("Test wiki space update"); -- W.Set_Is_Public (True); -- T.Manager.Save_Wiki_Space (W); -- -- T.Manager.Load_Wiki_Space (Wiki => W2, -- Id => W.Get_Id); -- Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), -- "Invalid wiki space name"); end Test_Increment; -- ------------------------------ -- Test creation of a wiki page. -- ------------------------------ procedure Test_Create_Wiki_Page (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]"); -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- -- P.Set_Name ("The page"); -- P.Set_Title ("The page title"); -- T.Manager.Create_Wiki_Page (W, P, C); -- T.Assert (P.Is_Inserted, "The new wiki page was not created"); end Test_Create_Wiki_Page; -- ------------------------------ -- Test creation of a wiki page content. -- ------------------------------ procedure Test_Create_Wiki_Content (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]"); -- W.Set_Name ("Test wiki space"); -- T.Manager.Create_Wiki_Space (W); -- -- P.Set_Name ("The page"); -- P.Set_Title ("The page title"); -- T.Manager.Create_Wiki_Page (W, P, C); -- -- C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN); -- C.Set_Content ("-- Title" & ASCII.LF & "A paragraph"); -- C.Set_Save_Comment ("A first version"); -- T.Manager.Create_Wiki_Content (P, C); -- T.Assert (C.Is_Inserted, "The new wiki content was not created"); -- T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author"); -- T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page"); end Test_Create_Wiki_Content; end AWA.Counters.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
45ed264abadd8a048b2cc655ba96e428de97f08b
awa/plugins/awa-settings/regtests/awa-settings-modules-tests.adb
awa/plugins/awa-settings/regtests/awa-settings-modules-tests.adb
----------------------------------------------------------------------- -- awa-settings-modules-tests -- Unit tests for settings module -- 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.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tests.Helpers.Contexts; package body AWA.Settings.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting", Test_Get_User_Setting'Access); end Add_Tests; -- ------------------------------ -- Test getting a user setting. -- ------------------------------ procedure Test_Get_User_Setting (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Tests.Helpers.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); for I in 1 .. 10 loop declare Name : constant String := "setting-" & Natural'Image (I); R : constant Integer := AWA.Settings.Get_User_Setting (Name, I); begin Util.Tests.Assert_Equals (T, I, R, "Invalid Get_User_Setting result"); end; end loop; end Test_Get_User_Setting; -- ------------------------------ -- Test saving a user setting. -- ------------------------------ procedure Test_Set_User_Setting (T : in out Test) is begin null; end Test_Set_User_Setting; end AWA.Settings.Modules.Tests;
----------------------------------------------------------------------- -- awa-settings-modules-tests -- Unit tests for settings module -- 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.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tests.Helpers.Contexts; package body AWA.Settings.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Settings.Get_User_Setting", Test_Get_User_Setting'Access); Caller.Add_Test (Suite, "Test AWA.Settings.Set_User_Setting", Test_Set_User_Setting'Access); end Add_Tests; -- ------------------------------ -- Test getting a user setting. -- ------------------------------ procedure Test_Get_User_Setting (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Tests.Helpers.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); for I in 1 .. 10 loop declare Name : constant String := "setting-" & Natural'Image (I); R : constant Integer := AWA.Settings.Get_User_Setting (Name, I); begin Util.Tests.Assert_Equals (T, I, R, "Invalid Get_User_Setting result"); end; end loop; end Test_Get_User_Setting; -- ------------------------------ -- Test saving a user setting. -- ------------------------------ procedure Test_Set_User_Setting (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Tests.Helpers.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); for I in 1 .. 10 loop declare Name : constant String := "setting-" & Natural'Image (I); R : Integer; begin AWA.Settings.Set_User_Setting (Name, I); R := AWA.Settings.Get_User_Setting (Name, 0); Util.Tests.Assert_Equals (T, I, R, "Invalid Set_User_Setting result"); end; end loop; end Test_Set_User_Setting; end AWA.Settings.Modules.Tests;
Add test for setting user setting
Add test for setting user setting
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a3e0672080878e749685ae94094100e1b9e22658
awa/plugins/awa-counters/src/awa-counters-modules.ads
awa/plugins/awa-counters/src/awa-counters-modules.ads
----------------------------------------------------------------------- -- awa-counters-modules -- Module counters -- Copyright (C) 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Calendar; with ASF.Applications; with ADO.Sessions; with AWA.Modules; -- == Integration == -- The `Counter_Module` manages the counters associated with database entities. -- To avoid having to update the database each time a counter is incremented, -- counters are kept temporarily in a `Counter_Table` protected type. -- The table contains only the partial increments and not the real counter -- values. Counters are flushed when the table reaches some limit, or, -- when the table is oldest than some limit. Counters are associated with -- a day so that it becomes possible to gather per-day counters. -- The table is also flushed when a counter is incremented in a different day. -- -- To be able to use the `Counters` module, you will need to add the -- following line in your GNAT project file: -- -- with "awa_counters"; -- -- An instance of the `Counter_Module` must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- with AWA.Counters.Modules; -- ... -- type Application is new AWA.Applications.Application with record -- Counter_Module : aliased AWA.Counters.Modules.Counter_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Counters.Modules.NAME, -- Module => App.Counter_Module'Access); -- -- == Configuration == -- The `counters` module defines the following configuration parameters: -- -- @include-config counters.xml -- package AWA.Counters.Modules is -- The name under which the module is registered. NAME : constant String := "counters"; -- Default age limit to flush counters: 5 minutes. DEFAULT_AGE_LIMIT : constant Duration := 5 * 60.0; -- Default maximum number of different counters to keep before flushing. DEFAULT_COUNTER_LIMIT : constant Natural := 1_000; PARAM_AGE_LIMIT : constant String := "counter_age_limit"; PARAM_COUNTER_LIMIT : constant String := "counter_limit"; -- ------------------------------ -- Module counters -- ------------------------------ type Counter_Module is new AWA.Modules.Module with private; type Counter_Module_Access is access all Counter_Module'Class; -- Initialize the counters module. overriding procedure Initialize (Plugin : in out Counter_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having -- read its XML configuration. overriding procedure Configure (Plugin : in out Counter_Module; Props : in ASF.Applications.Config); -- Get the counters module. function Get_Counter_Module return Counter_Module_Access; -- Increment the counter identified by `Counter` and associated with the -- database object `Object`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); -- Increment the counter identified by `Counter` and associated with the -- database object key `Key`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Increment the counter identified by `Counter`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type); -- Get the current counter value. procedure Get_Counter (Plugin : in out Counter_Module; Counter : in AWA.Counters.Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class; Result : out Natural); -- Flush the existing counters and update all the database records -- refered to them. procedure Flush (Plugin : in out Counter_Module); private type Definition_Array_Type is array (Counter_Index_Type range <>) of Natural; type Definition_Array_Type_Access is access all Definition_Array_Type; -- The counter map tracks a counter associated with a database object. -- All the database objects refer to the same counter. package Counter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => ADO.Objects.Object_Key, Element_Type => Positive, Hash => ADO.Objects.Hash, Equivalent_Keys => ADO.Objects."="); -- The `Counter_Map_Array` associate a counter map to each counter definition. type Counter_Map_Array is array (Counter_Index_Type range <>) of Counter_Maps.Map; type Counter_Map_Array_Access is access all Counter_Map_Array; -- Counters are kept temporarily in the `Counter_Table` protected type to avoid -- having to update the database each time a counter is incremented. -- Counters are flushed when the table reaches some limit, or, when the -- table is oldest than some limit. Counters are associated with a day -- so that it becomes possible to gather per-day counters. -- -- The `Flush` operation on the `Counter_Module` can be used to flush -- the pending counters. For each counter that was updated, it either -- inserts or updates a row in the counters database table. Because such -- operation is slow, it is not implemented in the protected type. -- Instead, we steal the counter table and replace it with a new/empty -- table. This is done by `Steal_Counters` protected operation. -- While doing the flush, other tasks can increment counters without -- being blocked by the `Flush` operation. protected type Counter_Table is -- Increment the counter identified by `Counter` and associated with the -- database object <tt>Key</tt>. procedure Increment (Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Get the counters that have been collected with the date and -- prepare to collect new counters. procedure Steal_Counters (Result : out Counter_Map_Array_Access; Date : out Ada.Calendar.Time); -- Check if we must flush the counters. function Need_Flush (Limit : in Natural; Seconds : in Duration) return Boolean; -- Get the definition ID associated with the counter. procedure Get_Definition (Session : in out ADO.Sessions.Master_Session; Counter : in Counter_Index_Type; Result : out Natural); private Day : Ada.Calendar.Time; Day_End : Ada.Calendar.Time; Counters : Counter_Map_Array_Access; Definitions : Definition_Array_Type_Access; Nb_Counters : Natural := 0; end Counter_Table; type Counter_Module is new AWA.Modules.Module with record Counters : Counter_Table; Counter_Limit : Natural := DEFAULT_COUNTER_LIMIT; Age_Limit : Duration := DEFAULT_AGE_LIMIT; end record; end AWA.Counters.Modules;
----------------------------------------------------------------------- -- awa-counters-modules -- Module counters -- Copyright (C) 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Calendar; with ASF.Applications; with ADO.Sessions; with AWA.Modules; -- == Integration == -- The `Counter_Module` manages the counters associated with database entities. -- To avoid having to update the database each time a counter is incremented, -- counters are kept temporarily in a `Counter_Table` protected type. -- The table contains only the partial increments and not the real counter -- values. Counters are flushed when the table reaches some limit, or, -- when the table is oldest than some limit. Counters are associated with -- a day so that it becomes possible to gather per-day counters. -- The table is also flushed when a counter is incremented in a different day. -- -- To be able to use the `Counters` module, you will need to add the -- following line in your GNAT project file: -- -- with "awa_counters"; -- -- An instance of the `Counter_Module` must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- with AWA.Counters.Modules; -- ... -- type Application is new AWA.Applications.Application with record -- Counter_Module : aliased AWA.Counters.Modules.Counter_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Counters.Modules.NAME, -- Module => App.Counter_Module'Access); -- -- == Configuration == -- The `counters` module defines the following configuration parameters: -- -- @include-config counters.xml -- package AWA.Counters.Modules is -- The name under which the module is registered. NAME : constant String := "counters"; -- Default age limit to flush counters: 5 minutes. DEFAULT_AGE_LIMIT : constant Duration := 5 * 60.0; -- Default maximum number of different counters to keep before flushing. DEFAULT_COUNTER_LIMIT : constant Natural := 1_000; PARAM_AGE_LIMIT : constant String := "counter_age_limit"; PARAM_COUNTER_LIMIT : constant String := "counter_limit"; -- ------------------------------ -- Module counters -- ------------------------------ type Counter_Module is new AWA.Modules.Module with private; type Counter_Module_Access is access all Counter_Module'Class; -- Initialize the counters module. overriding procedure Initialize (Plugin : in out Counter_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having -- read its XML configuration. overriding procedure Configure (Plugin : in out Counter_Module; Props : in ASF.Applications.Config); -- Get the counters module. function Get_Counter_Module return Counter_Module_Access; -- Increment the counter identified by `Counter` and associated with the -- database object `Object`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); -- Increment the counter identified by `Counter` and associated with the -- database object key `Key`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Increment the counter identified by `Counter`. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type); -- Get the current counter value. procedure Get_Counter (Plugin : in out Counter_Module; Counter : in AWA.Counters.Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class; Result : out Natural); -- Flush the existing counters and update all the database records -- refered to them. procedure Flush (Plugin : in out Counter_Module); private type Definition_Array_Type is array (Counter_Index_Type range <>) of Natural; type Definition_Array_Type_Access is access all Definition_Array_Type; -- The counter map tracks a counter associated with a database object. -- All the database objects refer to the same counter. package Counter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => ADO.Objects.Object_Key, Element_Type => Positive, Hash => ADO.Objects.Hash, Equivalent_Keys => ADO.Objects."="); -- The `Counter_Map_Array` associate a counter map to each counter definition. type Counter_Map_Array is array (Counter_Index_Type range <>) of Counter_Maps.Map; type Counter_Map_Array_Access is access all Counter_Map_Array; -- Counters are kept temporarily in the `Counter_Table` protected type to avoid -- having to update the database each time a counter is incremented. -- Counters are flushed when the table reaches some limit, or, when the -- table is oldest than some limit. Counters are associated with a day -- so that it becomes possible to gather per-day counters. -- -- The `Flush` operation on the `Counter_Module` can be used to flush -- the pending counters. For each counter that was updated, it either -- inserts or updates a row in the counters database table. Because such -- operation is slow, it is not implemented in the protected type. -- Instead, we steal the counter table and replace it with a new/empty -- table. This is done by `Steal_Counters` protected operation. -- While doing the flush, other tasks can increment counters without -- being blocked by the `Flush` operation. protected type Counter_Table is -- Increment the counter identified by `Counter` and associated with the -- database object <tt>Key</tt>. procedure Increment (Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Get the counters that have been collected with the date and -- prepare to collect new counters. procedure Steal_Counters (Result : out Counter_Map_Array_Access; Date : out Ada.Calendar.Time); -- Check if we must flush the counters. function Need_Flush (Limit : in Natural; Seconds : in Duration) return Boolean; -- Get the definition ID associated with the counter. procedure Get_Definition (Session : in out ADO.Sessions.Master_Session; Counter : in Counter_Index_Type; Result : out Natural); private Day : Ada.Calendar.Time; Day_End : Ada.Calendar.Time; Counters : Counter_Map_Array_Access; Definitions : Definition_Array_Type_Access; Nb_Counters : Natural := 0; end Counter_Table; type Counter_Module is new AWA.Modules.Module with record Counters : Counter_Table; Counter_Limit : Natural := DEFAULT_COUNTER_LIMIT; Age_Limit : Duration := DEFAULT_AGE_LIMIT; end record; end AWA.Counters.Modules;
Fix spurious space
Fix spurious space
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6dc87d57bc41f7332b52cb8011c446dee3b2186b
awa/plugins/awa-settings/src/awa-settings-modules.adb
awa/plugins/awa-settings/src/awa-settings-modules.adb
----------------------------------------------------------------------- -- awa-awa-settings-modules -- Module awa-settings -- 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.Unchecked_Deallocation; with ADO.Sessions; with ADO.Queries; with AWA.Services.Contexts; with AWA.Settings.Models; with AWA.Modules.Get; with AWA.Users.Models; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Beans.Basic; package body AWA.Settings.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Awa-settings.Module"); package ASC renames AWA.Services.Contexts; -- Load the setting value for the current user. -- Return the default value if there is no such setting. procedure Load (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String); -- Save the setting value for the current user. procedure Save (Name : in String; Value : in String); -- ------------------------------ -- Set the user setting with the given name in the setting manager cache -- and in the database. -- ------------------------------ procedure Set (Manager : in out Setting_Manager; Name : in String; Value : in String) is begin Manager.Data.Set (Name, Value); end Set; -- ------------------------------ -- Get the user setting with the given name from the setting manager cache. -- Load the user setting from the database if necessary. -- ------------------------------ procedure Get (Manager : in out Setting_Manager; Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is begin Manager.Data.Get (Name, Default, Value); end Get; -- ------------------------------ -- Get the current setting manager for the current user. -- ------------------------------ function Current return Setting_Manager_Access is Ctx : constant ASC.Service_Context_Access := ASC.Current; Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute ("AWA.Settings"); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Obj); begin if Bean = null or else not (Bean.all in Setting_Manager'Class) then declare Mgr : constant Setting_Manager_Access := new Setting_Manager; begin Obj := Util.Beans.Objects.To_Object (Mgr.all'Access); Ctx.Set_Session_Attribute ("AWA.Settings", Obj); return Mgr; end; else return Setting_Manager'Class (Bean.all)'Unchecked_Access; end if; end Current; -- ------------------------------ -- Initialize the settings module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the settings module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the settings module. -- ------------------------------ function Get_Setting_Module return Setting_Module_Access is function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME); begin return Get; end Get_Setting_Module; -- ------------------------------ -- Load the setting value for the current user. -- Return the default value if there is no such setting. -- ------------------------------ procedure Load (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Setting : AWA.Settings.Models.User_Setting_Ref; Found : Boolean; begin Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id "); Query.Set_Filter ("a.name = :name AND o.user_id = :user"); Query.Bind_Param ("name", Name); Query.Bind_Param ("user", User.Get_Id); Setting.Find (DB, Query, Found); if not Found then Value := Ada.Strings.Unbounded.To_Unbounded_String (Default); else Value := Setting.Get_Value; end if; end Load; -- Save the setting value for the current user. procedure Save (Name : in String; Value : in String) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Setting : AWA.Settings.Models.User_Setting_Ref; Query : ADO.Queries.Context; Found : Boolean; begin Ctx.Start; Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id "); Query.Set_Filter ("a.name = :name AND o.user_id = :user"); Query.Bind_Param ("name", Name); Query.Bind_Param ("user", User.Get_Id); Setting.Find (DB, Query, Found); if not Found then declare Setting_Def : AWA.Settings.Models.Setting_Ref; begin Query.Clear; Query.Set_Filter ("o.name = :name"); Query.Bind_Param ("name", Name); Setting_Def.Find (DB, Query, Found); if not Found then Setting_Def.Set_Name (Name); Setting_Def.Save (DB); end if; Setting.Set_Setting (Setting_Def); end; Setting.Set_User (User); end if; Setting.Set_Value (Value); Setting.Save (DB); Ctx.Commit; end Save; procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data, Name => Setting_Data_Access); use Ada.Strings.Unbounded; protected body Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then Value := Item.Value; if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Load (Name, Default, Value); Item := new Setting_Data; Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Item.Value := Value; Item.Next_Setting := First; First := Item; end Get; procedure Set (Name : in String; Value : in String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; if Item.Value = Value then return; end if; Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); Save (Name, Value); return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Item := new Setting_Data; Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); Item.Next_Setting := First; First := Item; Save (Name, Value); end Set; procedure Clear is begin while First /= null loop declare Item : Setting_Data_Access := First; begin First := Item.Next_Setting; Free (Item); end; end loop; end Clear; end Settings; end AWA.Settings.Modules;
----------------------------------------------------------------------- -- awa-settings-modules -- Module awa-settings -- 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.Unchecked_Deallocation; with ADO.Sessions; with ADO.Queries; with AWA.Services.Contexts; with AWA.Settings.Models; with AWA.Modules.Get; with AWA.Users.Models; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Beans.Basic; package body AWA.Settings.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Settings.Module"); package ASC renames AWA.Services.Contexts; -- Load the setting value for the current user. -- Return the default value if there is no such setting. procedure Load (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String); -- Save the setting value for the current user. procedure Save (Name : in String; Value : in String); -- ------------------------------ -- Set the user setting with the given name in the setting manager cache -- and in the database. -- ------------------------------ procedure Set (Manager : in out Setting_Manager; Name : in String; Value : in String) is begin Manager.Data.Set (Name, Value); end Set; -- ------------------------------ -- Get the user setting with the given name from the setting manager cache. -- Load the user setting from the database if necessary. -- ------------------------------ procedure Get (Manager : in out Setting_Manager; Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is begin Manager.Data.Get (Name, Default, Value); end Get; -- ------------------------------ -- Get the current setting manager for the current user. -- ------------------------------ function Current return Setting_Manager_Access is Ctx : constant ASC.Service_Context_Access := ASC.Current; Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute (SESSION_ATTR_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Obj); begin if Bean = null or else not (Bean.all in Setting_Manager'Class) then declare Mgr : constant Setting_Manager_Access := new Setting_Manager; begin Obj := Util.Beans.Objects.To_Object (Mgr.all'Access); Ctx.Set_Session_Attribute (SESSION_ATTR_NAME, Obj); return Mgr; end; else return Setting_Manager'Class (Bean.all)'Unchecked_Access; end if; end Current; -- ------------------------------ -- Initialize the settings module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the settings module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the settings module. -- ------------------------------ function Get_Setting_Module return Setting_Module_Access is function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME); begin return Get; end Get_Setting_Module; -- ------------------------------ -- Load the setting value for the current user. -- Return the default value if there is no such setting. -- ------------------------------ procedure Load (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.Queries.Context; Setting : AWA.Settings.Models.User_Setting_Ref; Found : Boolean; begin Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id "); Query.Set_Filter ("a.name = :name AND o.user_id = :user"); Query.Bind_Param ("name", Name); Query.Bind_Param ("user", User.Get_Id); Setting.Find (DB, Query, Found); if not Found then Value := Ada.Strings.Unbounded.To_Unbounded_String (Default); else Value := Setting.Get_Value; end if; end Load; -- Save the setting value for the current user. procedure Save (Name : in String; Value : in String) is Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Setting : AWA.Settings.Models.User_Setting_Ref; Query : ADO.Queries.Context; Found : Boolean; begin Ctx.Start; Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id "); Query.Set_Filter ("a.name = :name AND o.user_id = :user"); Query.Bind_Param ("name", Name); Query.Bind_Param ("user", User.Get_Id); Setting.Find (DB, Query, Found); if not Found then declare Setting_Def : AWA.Settings.Models.Setting_Ref; begin Query.Clear; Query.Set_Filter ("o.name = :name"); Query.Bind_Param ("name", Name); Setting_Def.Find (DB, Query, Found); if not Found then Setting_Def.Set_Name (Name); Setting_Def.Save (DB); end if; Setting.Set_Setting (Setting_Def); end; Setting.Set_User (User); end if; Setting.Set_Value (Value); Setting.Save (DB); Ctx.Commit; end Save; procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data, Name => Setting_Data_Access); use Ada.Strings.Unbounded; protected body Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then Value := Item.Value; if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Load (Name, Default, Value); Item := new Setting_Data; Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Item.Value := Value; Item.Next_Setting := First; First := Item; end Get; procedure Set (Name : in String; Value : in String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; if Item.Value = Value then return; end if; Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); Save (Name, Value); return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Item := new Setting_Data; Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); Item.Next_Setting := First; First := Item; Save (Name, Value); end Set; procedure Clear is begin while First /= null loop declare Item : Setting_Data_Access := First; begin First := Item.Next_Setting; Free (Item); end; end loop; end Clear; end Settings; end AWA.Settings.Modules;
Use the SESSION_ATTR_NAME constant to access the user settings
Use the SESSION_ATTR_NAME constant to access the user settings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b3c25a22063b6b3ec7dc4184f04b941adc4c5ec0
testutil/util-tests-servers.adb
testutil/util-tests-servers.adb
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with Util.Streams.Sockets; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is pragma Unreferenced (Into, Line, Stream); begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Address.Addr := Addresses (Get_Host_By_Name (S.Get_Host), 1); Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Input : Util.Streams.Texts.Reader_Stream; begin Instance.Client.Open (Socket); Input.Initialize (From => Instance.Client'Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line, Input, Instance.Client); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Instance.Client.Close; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class) is pragma Unreferenced (Into, Line, Stream); begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Address.Addr := Addresses (Get_Host_By_Name (S.Get_Host), 1); Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Input : Util.Streams.Texts.Reader_Stream; begin Instance.Client.Open (Socket); Input.Initialize (From => Instance.Client'Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line, Input, Instance.Client); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Instance.Client.Close; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
16caf1c3b149025de952ba68c7ff2bff4d39d506
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Wikis.Servlets; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; with Wiki.Strings; -- == Integration == -- The `Wiki_Module` manages the creation, update, removal of wiki pages in an application. -- It provides operations that are used by the wiki beans or other services to create and update -- wiki pages. An instance of the `Wiki_Module` must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Wikis.Modules.NAME, -- URI => "wikis", -- Module => App.Wiki_Module'Access); -- -- == Configuration == -- @include-config wikis.xml -- -- == Events == -- The `wikis` exposes a number of events which are posted when some action -- are performed at the service level. -- -- | Event name | Description | -- |:--------------------|:--------------------------------------------------------------| -- | wiki-create-page | This event is posted when a new wiki page is created. | -- | wiki-create-content | This event is posted when a new wiki page content is created. | -- | | Each time a wiki page is modified, a new wiki page content | -- | | is created and this event is posted. | -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- The configuration parameter that defines the page link prefix in rendered HTML content. PARAM_PAGE_PREFIX : constant String := "page_prefix"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Wiki_Module; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the page prefix that was configured for the Wiki module. function Get_Page_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); procedure Load_Image (Model : in Wiki_Module; Wiki_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Wikis.Servlets.Image_Servlet; Page_Prefix : Wiki.Strings.UString; end record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015, 2016, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Wikis.Servlets; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; with Wiki.Strings; -- == Integration == -- To be able to use the `Wikis` module, you will need to add the following -- line in your GNAT project file: -- -- with "awa_wikis"; -- -- The `Wiki_Module` manages the creation, update, removal of wiki pages -- in an application. It provides operations that are used by the wiki beans -- or other services to create and update wiki pages. An instance of -- the `Wiki_Module` must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- with AWA.Wikis.Modules; -- ... -- type Application is new AWA.Applications.Application with record -- Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Wikis.Modules.NAME, -- URI => "wikis", -- Module => App.Wiki_Module'Access); -- -- == Configuration == -- @include-config wikis.xml -- -- == Events == -- The `wikis` exposes a number of events which are posted when some action -- are performed at the service level. -- -- | Event name | Description | -- |:--------------------|:--------------------------------------------------------------| -- | wiki-create-page | This event is posted when a new wiki page is created. | -- | wiki-create-content | This event is posted when a new wiki page content is created. | -- | | Each time a wiki page is modified, a new wiki page content | -- | | is created and this event is posted. | -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- The configuration parameter that defines the image link prefix -- in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- The configuration parameter that defines the page link prefix -- in rendered HTML content. PARAM_PAGE_PREFIX : constant String := "page_prefix"; -- The configuration parameter that defines a list of wiki page ID -- to copy when a new wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Define the permissions. package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read -- its XML configuration. overriding procedure Configure (Plugin : in out Wiki_Module; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the page prefix that was configured for the Wiki module. function Get_Page_Prefix (Module : in Wiki_Module) return Wiki.Strings.UString; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in Models.Wiki_Space_Ref'Class; Page : in out Models.Wiki_Page_Ref'Class; Content : in out Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out Models.Wiki_Page_Ref'Class; Content : in out Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out Models.Wiki_Page_Ref'Class; Content : in out Models.Wiki_Content_Ref'Class); procedure Load_Image (Model : in Wiki_Module; Wiki_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out Models.Wiki_Page_Ref'Class; Content : in out Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Wikis.Servlets.Image_Servlet; Page_Prefix : Wiki.Strings.UString; end record; end AWA.Wikis.Modules;
Fix style and update the documentation
Fix style and update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
77ceca8cdc6981bbdb4968a1bce3763073fa26d4
regtests/util-http-clients-tests.ads
regtests/util-http-clients-tests.ads
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http OPTIONS operation. procedure Test_Http_Options (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
----------------------------------------------------------------------- -- util-http-clients-tests -- Unit tests for HTTP client -- Copyright (C) 2012, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Tests.Servers; with Util.Streams.Texts; with Util.Streams.Sockets; package Util.Http.Clients.Tests is type Method_Type is (OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH, CONNECT, UNKNOWN); type Test_Server is new Util.Tests.Servers.Server with record Method : Method_Type := UNKNOWN; Result : Ada.Strings.Unbounded.Unbounded_String; Content_Type : Ada.Strings.Unbounded.Unbounded_String; Length : Natural := 0; Test_Timeout : Boolean := False; end record; type Test_Server_Access is access all Test_Server'Class; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class; Client : in out Util.Streams.Sockets.Socket_Stream'Class); type Test is new Util.Tests.Test with record Server : Test_Server_Access := null; end record; -- Test the http Get operation. procedure Test_Http_Get (T : in out Test); -- Test the http POST operation. procedure Test_Http_Post (T : in out Test); -- Test the http PUT operation. procedure Test_Http_Put (T : in out Test); -- Test the http DELETE operation. procedure Test_Http_Delete (T : in out Test); -- Test the http OPTIONS operation. procedure Test_Http_Options (T : in out Test); -- Test the http PATCH operation. procedure Test_Http_Patch (T : in out Test); -- Test the http timeout. procedure Test_Http_Timeout (T : in out Test); overriding procedure Set_Up (T : in out Test); overriding procedure Tear_Down (T : in out Test); -- Get the test server base URI. function Get_Uri (T : in Test) return String; -- The <b>Http_Tests</b> package must be instantiated with one of the HTTP implementation. -- The <b>Register</b> procedure configures the Http.Client to use the given HTTP -- implementation before running the test. generic with procedure Register; NAME : in String; package Http_Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Http_Test is new Test with null record; overriding procedure Set_Up (T : in out Http_Test); end Http_Tests; end Util.Http.Clients.Tests;
Declare the Test_Http_Patch procedure and add the PATCH enum value
Declare the Test_Http_Patch procedure and add the PATCH enum value
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3d6172f520553bec62652a67063f6020864150c1
src/base/log/util-log-appenders-consoles.ads
src/base/log/util-log-appenders-consoles.ads
----------------------------------------------------------------------- -- util-log-appenders-consoles -- Console log appenders -- Copyright (C) 2001 - 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- Write log events to the console. package Util.Log.Appenders.Consoles is type Console_Appender (Length : Positive) is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type Console_Appender (Length : Positive) is new Appender (Length) with record Stderr : Boolean := False; Prefix : Util.Properties.Value; end record; end Util.Log.Appenders.Consoles;
----------------------------------------------------------------------- -- util-log-appenders-consoles -- Console log appenders -- Copyright (C) 2001 - 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- === Console appender === -- The `Console` appender recognises the following configurations: -- -- | Name | Description | -- | -------------- | -------------------------------------------------------------- | -- | layout | Defines the format of the message printed by the appender. | -- | level | Defines the minimum level above which messages are printed. | -- | stderr | When 'true' or '1', use the console standard error, | -- | | by default the appender uses the standard output | -- package Util.Log.Appenders.Consoles is type Console_Appender (Length : Positive) is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type Console_Appender (Length : Positive) is new Appender (Length) with record Stderr : Boolean := False; Prefix : Util.Properties.Value; end record; end Util.Log.Appenders.Consoles;
Add documentation for the configuration
Add documentation for the configuration
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9a741d7351ace8619a3db5cbcc38c3645efff6e2
awa/plugins/awa-setup/src/awa-setup-applications.ads
awa/plugins/awa-setup/src/awa-setup-applications.ads
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new ASF.Servlets.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
Declare the Redirect_Servlet type and override the Do_Get procedure
Declare the Redirect_Servlet type and override the Do_Get procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bca4f084cfda20fbb2c4e144dbfb7288314526b5
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Modules.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Modules.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Use AWA.Images.Modules.Tests package (migrated from AWA.Images.Services.Tests)
Use AWA.Images.Modules.Tests package (migrated from AWA.Images.Services.Tests)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
804679f97f41158e3175183a888fba7d72477263
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 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. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Lists.Node_List_Ref) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 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. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Parent => Into.Current, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0, Parent => Into.Current)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0, Parent => Into.Current)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0, Parent => Into.Current)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0, Parent => Into.Current)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0, Parent => Into.Current)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Parent => Into.Current, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Parent => Into.Current, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Parent => Into.Current, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Into : in out Document) is Table : Node_Type_Access; Row : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; -- Create the current table. if Table = null then Table := new Node_Type '(Kind => N_TABLE, Len => 0, Tag_Start => TABLE_TAG, Children => null, Parent => Into.Current, others => <>); Append (Into, Table); end if; -- Add the row. Row := new Node_Type '(Kind => N_ROW, Len => 0, Tag_Start => TR_TAG, Children => null, Parent => Table, others => <>); Append (Table, Row); Into.Current := Row; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Into : in out Document; Attributes : in out Wiki.Attributes.Attribute_List) is Row : Node_Type_Access; Col : Node_Type_Access; begin -- Identify the current row. Row := Into.Current; while Row /= null and then Row.Kind /= N_ROW loop Row := Row.Parent; end loop; -- Add the new column. Col := new Node_Type '(Kind => N_COLUMN, Len => 0, Tag_Start => TD_TAG, Children => null, Parent => Row, Attributes => Attributes); Append (Row, Col); Into.Current := Col; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Into : in out Document) is Table : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; if Table /= null then Into.Current := Table.Parent; else Into.Current := null; end if; end Finish_Table; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Lists.Node_List_Ref) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
Add support for wiki tables - implement Add_Row, Add_Column and Finish_Table
Add support for wiki tables - implement Add_Row, Add_Column and Finish_Table
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
33bbb3e529ee0821cf7a8cb7402aaa01d5e5ea06
awa/src/awa-users-filters.ads
awa/src/awa-users-filters.ads
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "user.auth-filter.redirect"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "user.verify-filter.redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Sessions; with ASF.Principals; with ASF.Filters; with ASF.Servlets; with ASF.Security.Filters; with AWA.Users.Principals; package AWA.Users.Filters is -- Set the user principal on the session associated with the ASF request. procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Authentication verification filter -- ------------------------------ -- The <b>Auth_Filter</b> verifies that the user has the permission to access -- a given page. If the user is not logged, it tries to login automatically -- by using some persistent cookie. When this fails, it redirects the -- user to a login page (configured by AUTH_FILTER_REDIRECT_PARAM property). type Auth_Filter is new ASF.Security.Filters.Auth_Filter with private; -- The configuration parameter which controls the redirection page -- when the user is not logged (this should be the login page). AUTH_FILTER_REDIRECT_PARAM : constant String := "user.auth-filter.redirect"; -- A temporary cookie used to store the URL for redirection after the login is successful. REDIRECT_COOKIE : constant String := "RURL"; -- Initialize the filter and configure the redirection URIs. overriding procedure Initialize (Filter : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Authenticate a user by using the auto-login cookie. This procedure is called if the -- current session does not have any principal. Based on the request and the optional -- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return -- a principal object. The principal object will be freed when the session is closed. -- If the user cannot be authenticated, the returned principal should be null. -- -- The default implementation returns a null principal. overriding procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access); -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- Verify access key filter -- ------------------------------ -- The <b>Verify_Filter</b> filter verifies an access key associated to a user. -- The access key should have been sent to the user by some mechanism (email). -- The access key must be valid, that is an <b>Access_Key</b> database entry -- must exist and it must be associated with an email address and a user. type Verify_Filter is new ASF.Filters.Filter with private; -- The request parameter that <b>Verify_Filter</b> will check. PARAM_ACCESS_KEY : constant String := "key"; -- The configuration parameter which controls the redirection page -- when the access key is invalid. VERIFY_FILTER_REDIRECT_PARAM : constant String := "user.verify-filter.redirect"; -- Initialize the filter and configure the redirection URIs. procedure Initialize (Filter : in out Verify_Filter; Context : in ASF.Servlets.Servlet_Registry'Class); -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain); private use Ada.Strings.Unbounded; type Auth_Filter is new ASF.Security.Filters.Auth_Filter with record Login_URI : Unbounded_String; end record; type Verify_Filter is new ASF.Filters.Filter with record Invalid_Key_URI : Unbounded_String; end record; end AWA.Users.Filters;
Declare the REDIRECT_COOKIE constant
Declare the REDIRECT_COOKIE constant
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4b6843f59c89643c6e6dad217d5748ea73ca1e6e
src/gen-model-mappings.ads
src/gen-model-mappings.ads
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_BEAN, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
Add T_BEAN
Add T_BEAN
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4b430d3311b444c9c8100f38ff9f32276d155b03
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Probe_Event_Type is record Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Positive := 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 : Natural := 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; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); private Current : Event_Block_Access := null; Events : Event_Map; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Probe_Event_Type is record Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Time; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Positive := 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 : Natural := 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; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); private Current : Event_Block_Access := null; Events : Event_Map; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Declare the Get_Time_Range procedure on the Target_Events
Declare the Get_Time_Range procedure on the Target_Events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fde46f33084853e57a31b642528d9655c9d9e456
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; end Memory_Allocator; end MAT.Memory.Targets;
Implement the Probe_Free operation
Implement the Probe_Free operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e5317fe95fd0499fe1a3ef6479ce1521f8b0d334
src/util-streams-texts.ads
src/util-streams-texts.ads
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Texts.Transforms; with Ada.Characters.Handling; with Ada.Calendar; with GNAT.Calendar.Time_IO; package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Buffered_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Buffered_Stream) return String; package TR is new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream, Char => Character, Input => String, Put => Buffered.Write, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower, To_Input => To_String); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Buffered_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Buffered_Stream with null record; type Reader_Stream is new Buffered.Buffered_Stream with null record; end Util.Streams.Texts;
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- 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. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Texts.Transforms; with Ada.Characters.Handling; with Ada.Calendar; with GNAT.Calendar.Time_IO; package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Buffered_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Buffered_Stream) return String; package TR is new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream, Char => Character, Input => String, Put => Buffered.Write, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Buffered_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Buffered_Stream with null record; type Reader_Stream is new Buffered.Buffered_Stream with null record; end Util.Streams.Texts;
Update the Transforms package instantiation
Update the Transforms package instantiation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bcdfa62c1b205140d0c9a9e589637537dc6c1f2d
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; end record; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; end record; end MAT.Targets;
Declare the Console procedure
Declare the Console procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
754d1dac4d4ab2646d52128d8468e4fae6e12838
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); end if; return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Bean.Set_Name (Part.Get_Name); Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin return Models.Storage_Info_List_Bean (List).Get_Value (Name); end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Storage_List_Bean_Access := new Storage_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER); begin Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Folder_Id = ADO.NO_IDENTIFIER then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Folder_Id); end if; AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Bean.Set_Name (Part.Get_Name); Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin return Models.Storage_Info_List_Bean (List).Get_Value (Name); end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Storage_List_Bean_Access := new Storage_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER); begin Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Folder_Id = ADO.NO_IDENTIFIER then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Folder_Id); end if; AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Load the storage object
Load the storage object
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
d3b8781fddff10cd011b74137c8029d353f818f1
testcases/spatial1/spatial1.adb
testcases/spatial1/spatial1.adb
with Ada.Text_IO; with Spatial_Data; Use Spatial_Data; procedure Spatial1 is package TIO renames Ada.Text_IO; procedure print (shape : Geometry; label : String); procedure print (shape : Geometry; label : String) is begin TIO.Put_Line ("===== " & label & " ====="); TIO.Put_Line ("MySQL: " & mysql_text (shape)); TIO.Put_Line (" WKT: " & shape.Well_Known_Text); -- (shape)); TIO.Put_Line (""); end print; my_point : Geometry := initialize_as_point ((18.2, -3.4)); my_line : Geometry := initialize_as_line (((4.0, 2.23), (0.25, 5.1))); my_linestr : Geometry := initialize_as_line_string (((0.5, 2.0), (11.0, 4.4), (12.0, 8.1))); my_polygon : Geometry := initialize_as_polygon (((0.5, 2.0), (11.0, 4.4), (12.0, 8.1), (0.005, 2.0))); begin print (my_point, "SINGLE POINT"); print (my_line, "SINGLE LINE"); print (my_linestr, "SINGLE LINE STRING (THREE POINT)"); print (my_polygon, "SINGLE POLYGON (3 SIDES)"); end Spatial1;
with Ada.Text_IO; with Spatial_Data; Use Spatial_Data; procedure Spatial1 is package TIO renames Ada.Text_IO; procedure print (shape : Geometry; label : String); procedure print (shape : Geometry; label : String) is begin TIO.Put_Line ("===== " & label & " ====="); TIO.Put_Line ("MySQL: " & mysql_text (shape)); TIO.Put_Line (" WKT: " & Well_Known_Text (shape)); -- (shape)); TIO.Put_Line (""); end print; my_point : Geometry := initialize_as_point ((18.2, -3.4)); my_line : Geometry := initialize_as_line (((4.0, 2.23), (0.25, 5.1))); my_linestr : Geometry := initialize_as_line_string (((0.5, 2.0), (11.0, 4.4), (12.0, 8.1))); my_polygon : Geometry := initialize_as_polygon (((0.5, 2.0), (11.0, 4.4), (12.0, 8.1), (0.005, 2.0))); my_circle : Geometry := initialize_as_circle (((2.0, 1.0), 4.5)); my_infline : Geometry := initialize_as_infinite_line (((0.0, 0.0), (2.0, 2.0))); begin print (my_point, "SINGLE POINT"); print (my_line, "SINGLE LINE"); print (my_linestr, "SINGLE LINE STRING (THREE POINT)"); print (my_polygon, "SINGLE POLYGON (3 SIDES)"); print (my_circle, "SINGLE CIRCLE (not legal for MySQL or WKT)"); print (my_infline, "INFINITE LINE (converted to regular line on MySQL or WKT)"); -- convert my point to to a multi-point collection declare pt1 : Geometric_point := (9.2, 4.773); pt2 : Geometric_point := (-7.01, -4.9234); pt3 : Geometric_point := (4.5, 6.0); begin append_point (my_point, pt1); append_point (my_point, pt2); print (my_point, "MULTIPOINT COLLECTION"); append_line_string (my_linestr, ((pt3, pt1, pt2))); print (my_linestr, "MULTILINESTRING COLLECTION"); append_point (my_linestr, pt1); append_point (my_linestr, pt2); print (my_linestr, "MIXED COLLECTION #1"); append_point (my_line, pt1); append_point (my_line, pt2); print (my_line, "MIXED COLLECTION #2"); append_polygon_hole (my_polygon, ((1.0, 2.0), (3.2, 4.5), (8.8, 7.7), (1.0, 2.0))); append_point (my_polygon, pt1); append_point (my_polygon, pt2); print (my_polygon, "MIXED COLLECTION #3"); end; end Spatial1;
update spatial testcase
update spatial testcase
Ada
isc
jrmarino/AdaBase
a25a16d3a2e56ffc5f0e6387795e8b99887230b2
src/unix.adb
src/unix.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with GNAT.OS_Lib; with Ada.Text_IO; with Parameters; with System; package body Unix is package OSL renames GNAT.OS_Lib; package TIO renames Ada.Text_IO; package PM renames Parameters; ---------------------- -- process_status -- ---------------------- function process_status (pid : pid_t) return process_exit is result : constant uInt8 := nohang_waitpid (pid); begin case result is when 0 => return still_running; when 1 => return exited_normally; when others => return exited_with_error; end case; end process_status; ----------------------- -- screen_attached -- ----------------------- function screen_attached return Boolean is begin return CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 1; end screen_attached; ----------------------- -- cone_of_silence -- ----------------------- procedure cone_of_silence (deploy : Boolean) is result : uInt8; begin if not screen_attached then return; end if; if deploy then result := silent_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control OFF command failed"); end if; else result := chatty_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control ON command failed"); end if; end if; end cone_of_silence; ------------------------- -- kill_process_tree -- ------------------------- procedure kill_process_tree (process_group : pid_t) is pgid : constant String := process_group'Img; dfly_cmd : constant String := "/usr/bin/pkill -KILL -g"; free_cmd : constant String := "/bin/pkill -KILL -g"; killres : Boolean; begin if JT.equivalent (PM.configuration.operating_sys, "FreeBSD") then killres := external_command (free_cmd & pgid); else killres := external_command (dfly_cmd & pgid); end if; end kill_process_tree; ------------------------ -- external_command -- ------------------------ function external_command (command : String) return Boolean is Args : OSL.Argument_List_Access; Exit_Status : Integer; begin Args := OSL.Argument_String_To_List (command); Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return Exit_Status = 0; end external_command; ------------------- -- fork_failed -- ------------------- function fork_failed (pid : pid_t) return Boolean is begin if pid < 0 then return True; end if; return False; end fork_failed; ---------------------- -- launch_process -- ---------------------- function launch_process (command : String) return pid_t is procid : OSL.Process_Id; Args : OSL.Argument_List_Access; begin Args := OSL.Argument_String_To_List (command); procid := OSL.Non_Blocking_Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return pid_t (OSL.Pid_To_Integer (procid)); end launch_process; ---------------------------- -- env_variable_defined -- ---------------------------- function env_variable_defined (variable : String) return Boolean is test : String := OSL.Getenv (variable).all; begin return (test /= ""); end env_variable_defined; -------------------------- -- env_variable_value -- -------------------------- function env_variable_value (variable : String) return String is begin return OSL.Getenv (variable).all; end env_variable_value; ------------------ -- pipe_close -- ------------------ function pipe_close (OpenFile : CSM.FILEs) return Integer is res : constant CSM.int := pclose (FileStream => OpenFile); u16 : Interfaces.Unsigned_16; begin u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8); if Integer (u16) > 0 then return Integer (u16); end if; return Integer (res); end pipe_close; --------------------- -- piped_command -- --------------------- function piped_command (command : String; status : out Integer) return JT.Text is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return result; end piped_command; -------------------------- -- piped_mute_command -- -------------------------- function piped_mute_command (command : String; abnormal : out JT.Text) return Boolean is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; status : Integer; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); abnormal := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return status = 0; end piped_mute_command; ----------------- -- pipe_read -- ----------------- function pipe_read (OpenFile : CSM.FILEs) return JT.Text is -- Allocate 2kb at a time buffer : String (1 .. 2048) := (others => ' '); result : JT.Text := JT.blank; charbuf : CSM.int; marker : Natural := 0; begin loop charbuf := CSM.fgetc (OpenFile); if charbuf = CSM.EOF then if marker >= buffer'First then JT.SU.Append (result, buffer (buffer'First .. marker)); end if; exit; end if; if marker = buffer'Last then JT.SU.Append (result, buffer); marker := buffer'First; else marker := marker + 1; end if; buffer (marker) := Character'Val (charbuf); end loop; return result; end pipe_read; ----------------- -- true_path -- ----------------- function true_path (provided_path : String) return String is use type ICS.chars_ptr; buffer : IC.char_array (0 .. 1024) := (others => IC.nul); result : ICS.chars_ptr; path : IC.char_array := IC.To_C (provided_path); begin result := realpath (pathname => path, resolved_path => buffer); if result = ICS.Null_Ptr then return ""; end if; return ICS.Value (result); exception when others => return ""; end true_path; end Unix;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with GNAT.OS_Lib; with Ada.Text_IO; with Parameters; with System; package body Unix is package OSL renames GNAT.OS_Lib; package TIO renames Ada.Text_IO; package PM renames Parameters; ---------------------- -- process_status -- ---------------------- function process_status (pid : pid_t) return process_exit is result : constant uInt8 := nohang_waitpid (pid); begin case result is when 0 => return still_running; when 1 => return exited_normally; when others => return exited_with_error; end case; end process_status; ----------------------- -- screen_attached -- ----------------------- function screen_attached return Boolean is begin return CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 1; end screen_attached; ----------------------- -- cone_of_silence -- ----------------------- procedure cone_of_silence (deploy : Boolean) is result : uInt8; begin if not screen_attached then return; end if; if deploy then result := silent_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control OFF command failed"); end if; else result := chatty_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control ON command failed"); end if; end if; end cone_of_silence; ------------------------- -- kill_process_tree -- ------------------------- procedure kill_process_tree (process_group : pid_t) is pgid : constant String := process_group'Img; dfly_cmd : constant String := "/usr/bin/pkill -KILL -g"; free_cmd : constant String := "/bin/pkill -KILL -g"; killres : Boolean; begin if JT.equivalent (PM.configuration.operating_sys, "FreeBSD") then killres := external_command (free_cmd & pgid); else killres := external_command (dfly_cmd & pgid); end if; end kill_process_tree; ------------------------ -- external_command -- ------------------------ function external_command (command : String) return Boolean is Args : OSL.Argument_List_Access; Exit_Status : Integer; begin Args := OSL.Argument_String_To_List (command); Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return Exit_Status = 0; end external_command; ------------------- -- fork_failed -- ------------------- function fork_failed (pid : pid_t) return Boolean is begin if pid < 0 then return True; end if; return False; end fork_failed; ---------------------- -- launch_process -- ---------------------- function launch_process (command : String) return pid_t is procid : OSL.Process_Id; Args : OSL.Argument_List_Access; begin Args := OSL.Argument_String_To_List (command); procid := OSL.Non_Blocking_Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return pid_t (OSL.Pid_To_Integer (procid)); end launch_process; ---------------------------- -- env_variable_defined -- ---------------------------- function env_variable_defined (variable : String) return Boolean is test : String := OSL.Getenv (variable).all; begin return (test /= ""); end env_variable_defined; -------------------------- -- env_variable_value -- -------------------------- function env_variable_value (variable : String) return String is begin return OSL.Getenv (variable).all; end env_variable_value; ------------------ -- pipe_close -- ------------------ function pipe_close (OpenFile : CSM.FILEs) return Integer is res : constant CSM.int := pclose (FileStream => OpenFile); u16 : Interfaces.Unsigned_16; begin u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8); if Integer (u16) > 0 then return Integer (u16); end if; return Integer (res); end pipe_close; --------------------- -- piped_command -- --------------------- function piped_command (command : String; status : out Integer) return JT.Text is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("re")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return result; end piped_command; -------------------------- -- piped_mute_command -- -------------------------- function piped_mute_command (command : String; abnormal : out JT.Text) return Boolean is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; status : Integer; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("re")); abnormal := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return status = 0; end piped_mute_command; ----------------- -- pipe_read -- ----------------- function pipe_read (OpenFile : CSM.FILEs) return JT.Text is -- Allocate 2kb at a time buffer : String (1 .. 2048) := (others => ' '); result : JT.Text := JT.blank; charbuf : CSM.int; marker : Natural := 0; begin loop charbuf := CSM.fgetc (OpenFile); if charbuf = CSM.EOF then if marker >= buffer'First then JT.SU.Append (result, buffer (buffer'First .. marker)); end if; exit; end if; if marker = buffer'Last then JT.SU.Append (result, buffer); marker := buffer'First; else marker := marker + 1; end if; buffer (marker) := Character'Val (charbuf); end loop; return result; end pipe_read; ----------------- -- true_path -- ----------------- function true_path (provided_path : String) return String is use type ICS.chars_ptr; buffer : IC.char_array (0 .. 1024) := (others => IC.nul); result : ICS.chars_ptr; path : IC.char_array := IC.To_C (provided_path); begin result := realpath (pathname => path, resolved_path => buffer); if result = ICS.Null_Ptr then return ""; end if; return ICS.Value (result); exception when others => return ""; end true_path; end Unix;
Set close-on-exec property on popen commands
Set close-on-exec property on popen commands This is not supported on FreeBSD 9 nor DF 4.4. The ports makefile needs to handle removing this.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
438829a8195e91c35a6bd81b4001de594c82dc0c
src/util-texts-builders.ads
src/util-texts-builders.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- 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.Finalization; -- == Description == -- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an <tt>Append</tt> procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the <tt>Iterate</tt> operation that allows to get the content -- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- == Example == -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that recieves -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the <tt>Iterate</tt> operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- 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); -- 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); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- 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)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Description == -- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an <tt>Append</tt> procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the <tt>Iterate</tt> operation that allows to get the content -- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- == Example == -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that recieves -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the <tt>Iterate</tt> operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- 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); -- 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); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- 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)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
Update the header and use a private with clause for Ada.Finalization
Update the header and use a private with clause for Ada.Finalization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5537a6b2aa695fbe3939426a285075680d503834
src/wiki.ads
src/wiki.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; end Wiki;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
6c176f9a5615723fc573c18cf1698919d3bf6eee
matp/src/events/mat-events-probes.adb
matp/src/events/mat-events-probes.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; exception when E : others => Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count)); raise; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. -- ------------------------------ procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Targets.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Targets.Event_Id_Type) is begin Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id); end Update_Event; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; exception when E : others => Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count)); raise; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
Implement the Update_Event procedure
Implement the Update_Event procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b4e4c7996b41b1ce7e655d1b73c28df992639587
regtests/util-commands-tests.adb
regtests/util-commands-tests.adb
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type); -- Write the help associated with the command. procedure Help (Command : in out Test_Command_Type; Name : in String; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type) is pragma Unreferenced (Context); begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Test_Command_Type; Name : in String; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); declare Ctx : Test_Context_Type; begin D.Usage (Args, Ctx); C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type); -- Write the help associated with the command. procedure Help (Command : in out Test_Command_Type; Name : in String; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Test_Context_Type) is pragma Unreferenced (Context); begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Test_Command_Type; Name : in String; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_Help := False; C2.Expect_Help := False; Initialize (Args, "help"); D.Execute ("help", Args, Ctx); T.Assert (not Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin Initialize (Args, "help missing"); D.Execute ("help", Args, Ctx); T.Fail ("No exception raised for missing command"); exception when Not_Found => null; end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); declare Ctx : Test_Context_Type; begin D.Usage (Args, Ctx); C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); D.Usage (Args, Ctx, "list"); end; end Test_Usage; end Util.Commands.Tests;
Add more test on command help
Add more test on command help
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3b9c12b923b2849ca0f51e867f8b37e75a49fe44
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Util.Refs.Ref_Entity with Kind => N_NOT, Expr => Expr.Node); return Result; end Create_Not; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); return Result; end Create_Not; end MAT.Expressions;
Update the Create_Not operation
Update the Create_Not operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fcec9df9aad46449994e9b889890d9e6b6cd1561
src/wiki-streams.ads
src/wiki-streams.ads
----------------------------------------------------------------------- -- wiki-streams -- Wiki input and output streams -- 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. ----------------------------------------------------------------------- -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams is type Input_Stream is limited interface; -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. procedure Read (Input : in out Input_Stream; Char : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Output_Stream is limited interface; type Output_Stream_Type_Access is access all Output_Stream'Class; procedure Write (Stream : in out Output_Stream; Content : in Wide_Wide_String) is abstract; -- Write a single character to the string builder. procedure Write (Stream : in out Output_Stream; Char : in Wide_Wide_Character) is abstract; end Wiki.Streams;
----------------------------------------------------------------------- -- wiki-streams -- Wiki input and output streams -- 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. ----------------------------------------------------------------------- -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams is type Input_Stream is limited interface; -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. procedure Read (Input : in out Input_Stream; Char : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; procedure Write (Stream : in out Output_Stream; Content : in Wide_Wide_String) is abstract; -- Write a single character to the string builder. procedure Write (Stream : in out Output_Stream; Char : in Wide_Wide_Character) is abstract; end Wiki.Streams;
Rename Output_Stream_Type_Access into Output_Stream_Access
Rename Output_Stream_Type_Access into Output_Stream_Access
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
42d4e356202bbc478da36a441e332325db27dad1
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.ads
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Verify the anonymous access for the invitation page. procedure Verify_Anonymous (T : in out Test; Key : in String); -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with ADO; with AWA.Tests; package AWA.Workspaces.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Member_Id : ADO.Identifier; end record; -- Verify the anonymous access for the invitation page. procedure Verify_Anonymous (T : in out Test; Key : in String); -- Test sending an invitation. procedure Test_Invite_User (T : in out Test); -- Test deleting the member. procedure Test_Delete_Member (T : in out Test); end AWA.Workspaces.Tests;
Declare the Test_Delete_Member procedure
Declare the Test_Delete_Member procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
778cdc6ae4c14f1b1d7d1859a66b7518409549fa
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 Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- 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 Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) 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 Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.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; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.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 procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); 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); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; 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 : Wiki.Strings.WChar; 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 C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; 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; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); 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); Add_Element (Name); 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 Wiki.Strings.WChar) 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 : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (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, Wiki.Strings.To_WChar (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 Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- 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 Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) 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 Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin 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; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.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; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.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 procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); 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); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; 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 : Wiki.Strings.WChar; 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 C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := False; end if; else End_Element (P, Tag); end if; 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; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); 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); Add_Element (Name); 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 Wiki.Strings.WChar) 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 : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (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, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Use the wiki context Is_Hidden attribute
Use the wiki context Is_Hidden attribute
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
502b5c5ea31def6740ee3235da2ea557672e5c86
regtests/asf-routes-tests.ads
regtests/asf-routes-tests.ads
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Routes.Tests is -- A test bean to verify the path parameter injection. type Test_Bean is new Util.Beans.Basic.Bean with record Id : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Test_Bean_Access is access all Test_Bean; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); MAX_TEST_ROUTES : constant Positive := 100; type Test_Route_Type is new Route_Type with record Index : Natural := 0; end record; type Test_Route_Type_Access is access Test_Route_Type; type Test_Route_Array is array (1 .. MAX_TEST_ROUTES) of Test_Route_Type_Access; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new ASF.Tests.EL_Test with record Routes : Test_Route_Array; Bean : Test_Bean_Access; end record; -- Setup the test instance. overriding procedure Set_Up (T : in out Test); -- Verify that the path matches the given route. procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Add the route associted with the path pattern. procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html procedure Test_Add_Route_With_Path (T : in out Test); -- Test the Add_Route with extension mapping. -- Example: /list/*.html procedure Test_Add_Route_With_Ext (T : in out Test); -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html procedure Test_Add_Route_With_Param (T : in out Test); -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html procedure Test_Add_Route_With_EL (T : in out Test); -- Test the Iterate over several paths. procedure Test_Iterate (T : in out Test); end ASF.Routes.Tests;
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Routes.Tests is -- A test bean to verify the path parameter injection. type Test_Bean is new Util.Beans.Basic.Bean with record Id : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Test_Bean_Access is access all Test_Bean; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); MAX_TEST_ROUTES : constant Positive := 100; type Test_Route_Type is new Route_Type with record Index : Natural := 0; end record; type Test_Route_Type_Access is access Test_Route_Type; type Test_Route_Array is array (1 .. MAX_TEST_ROUTES) of Route_Type_Ref; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new ASF.Tests.EL_Test with record Routes : Test_Route_Array; Bean : Test_Bean_Access; end record; -- Setup the test instance. overriding procedure Set_Up (T : in out Test); -- Verify that the path matches the given route. procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Add the route associted with the path pattern. procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html procedure Test_Add_Route_With_Path (T : in out Test); -- Test the Add_Route with extension mapping. -- Example: /list/*.html procedure Test_Add_Route_With_Ext (T : in out Test); -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html procedure Test_Add_Route_With_Param (T : in out Test); -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html procedure Test_Add_Route_With_EL (T : in out Test); -- Test the Iterate over several paths. procedure Test_Iterate (T : in out Test); end ASF.Routes.Tests;
Change the Test_Route_Array to use the Route_Type_Ref
Change the Test_Route_Array to use the Route_Type_Ref
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
81bf1aeedd9129a85330ea26846208baf4e33055
src/util-commands-drivers.ads
src/util-commands-drivers.ads
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; Driver_Name : String := "Drivers"; package Util.Commands.Drivers is -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in Command_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Commands.Parsers; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>); Driver_Name : String := "Drivers"; package Util.Commands.Drivers is subtype Config_Type is Config_Parser.Config_Type; -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Command_Type; Config : in out Config_Type) is null; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in Command_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
Add a Config_Parser package parameter to the generic Define the Setup procedure on a Command_Type to setup the command options
Add a Config_Parser package parameter to the generic Define the Setup procedure on a Command_Type to setup the command options
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d45d33d00acac35253710382013ecea08c5dc645
awa/plugins/awa-setup/src/awa-setup-applications.ads
awa/plugins/awa-setup/src/awa-setup-applications.ads
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new ASF.Servlets.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications.Main; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Requests; with ASF.Responses; with ASF.Server; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Beans.Methods; with ADO.Drivers.Connections; package AWA.Setup.Applications is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Redirect_Servlet is new ASF.Servlets.Servlet with null record; overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); type Application is new ASF.Applications.Main.Application and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Redirect : aliased Redirect_Servlet; Config : ASF.Applications.Config; Changed : ASF.Applications.Config; Factory : ASF.Applications.Main.Application_Factory; Path : Ada.Strings.Unbounded.Unbounded_String; Database : ADO.Drivers.Connections.Configuration; Driver : Util.Beans.Objects.Object; Result : Util.Beans.Objects.Object; Done : Boolean := False; pragma Atomic (Done); pragma Volatile (Done); end record; -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the database connection string to be used by the application. function Get_Database_URL (From : in Application) return String; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class); end AWA.Setup.Applications;
Add a Driver and Result attribute to the setup Application type
Add a Driver and Result attribute to the setup Application type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ee61f7ae2881d9fb36c3fc870f6e8d65a8ec4318
awa/plugins/awa-storages/src/awa-storages-stores.ads
awa/plugins/awa-storages/src/awa-storages-stores.ads
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. -- -- @include awa-storages-stores-databases.ads -- @include awa-storages-stores-files.ads package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Create a storage procedure Create (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; -- Load the storage item represented by `From` in a file that can be accessed locally. procedure Load (Storage : in Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is abstract; end AWA.Storages.Stores;
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. The store can be a file system, a database -- or a remote store service. -- -- @include awa-storages-stores-databases.ads -- @include awa-storages-stores-files.ads package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Create a storage procedure Create (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; -- Load the storage item represented by `From` in a file that can be accessed locally. procedure Load (Storage : in Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is abstract; -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is abstract; end AWA.Storages.Stores;
Update comment
Update comment
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
01aa6c547de8d2ac5c57e2d9577d90df15825992
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; package AWA.Workspaces.Modules is -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
Declare the Not_Found exception
Declare the Not_Found exception
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
08094270ed5c66c3d391eeac548fb81631bb9509
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules; package body AWA.Applications is -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in ASF.Applications.Main.Application_Factory'Class) is URI : constant String := Conf.Get ("database"); begin ASF.Applications.Main.Application (App).Initialize (Conf, Factory); App.Factory.Create (URI); end Initialize; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Access, Name, URI); Module.Initialize (App); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.Factory.Get_Master_Session; end Get_Master_Session; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Modules; package body AWA.Applications is -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in ASF.Applications.Main.Application_Factory'Class) is URI : constant String := Conf.Get ("database"); begin ASF.Applications.Main.Application (App).Initialize (Conf, Factory); App.Factory.Create (URI); end Initialize; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin Module.Initialize (App); App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.Factory.Get_Master_Session; end Get_Master_Session; end AWA.Applications;
Fix initialization of the AWA application
Fix initialization of the AWA application
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
4fd8cbb6a0de948e12962f9d6e9c9b6a8d0de595
matp/src/memory/mat-memory-targets.ads
matp/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Events.Probes; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Events.Probes; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; Used_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in out Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Add the Used_Count for the memory stats
Add the Used_Count for the memory stats
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c5fc5a0d6583828ea1206e30be30a4d132216b05
src/gen-model-mappings.ads
src/gen-model-mappings.ads
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_BEAN, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition; type Mapping_Definition_Access is access all Mapping_Definition'Class; type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; Allow_Null : Mapping_Definition_Access; Nullable : 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 : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access; -- Get the type name. function Get_Type_Name (From : Mapping_Definition) return String; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_ENTITY_TYPE, T_BEAN, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition; type Mapping_Definition_Access is access all Mapping_Definition'Class; type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; Allow_Null : Mapping_Definition_Access; Nullable : 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 : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access; -- Get the type name. function Get_Type_Name (From : Mapping_Definition) return String; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type); -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
Add T_ENTITY_TYPE to the Basic_Type enumeration
Add T_ENTITY_TYPE to the Basic_Type enumeration
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
f505788325a12d7e7a09a7c947a6dcb0f8f583f3
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- 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 Wiki.Attributes; 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 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 text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.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); -- 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.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; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- 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 Wiki.Attributes; 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 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 text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String); -- 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.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; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); end Wiki.Render.Html;
Rename Add_Preformatted into Render_Preformatted
Rename Add_Preformatted into Render_Preformatted
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c43e0602ccf9b36f0777948ec8cf96f2bb531e7a
src/asf-views-nodes-jsf.ads
src/asf-views-nodes-jsf.ads
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- 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 ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
Change the Name parameter to a Binding access
Change the Name parameter to a Binding access
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
860c794a3bf7c93c4bb981efaeaadad7f7503644
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ADO.Drivers.Connections; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is procedure Free is new Ada.Unchecked_Deallocation (Object => String, Name => Ada.Strings.Unbounded.String_Access); Paths : constant String := Config.Get_Property ("ado.queries.paths"); Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); Query : Query_Definition_Access := File.Queries; begin Manager.Files (File.File).File := File; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is Paths : constant String := Config.Get_Property ("ado.queries.paths"); Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-ado
0414f291864bbaa7565304b8520a3cc47b99fce4
src/asf-beans-resolvers.ads
src/asf-beans-resolvers.ads
----------------------------------------------------------------------- -- asf-beans-resolvers -- Resolver to create and give access to managed beans -- 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.Finalization; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with EL.Contexts; with ASF.Applications.Main; with ASF.Requests; package ASF.Beans.Resolvers is -- ------------------------------ -- Bean Resolver -- ------------------------------ type ELResolver is limited new EL.Contexts.ELResolver with private; -- Initialize the EL resolver to use the application bean factory and the given request. procedure Initialize (Resolver : in out ELResolver; App : in ASF.Applications.Main.Application_Access; Request : in ASF.Requests.Request_Access); -- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>. -- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam). -- It then looks in the request and session attributes for the value. If the value was -- not in the request or session, it uses the application bean factory to create the -- new managed bean and adds it to the request or session. overriding function Get_Value (Resolver : in ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Ada.Strings.Unbounded.Unbounded_String) return Util.Beans.Objects.Object; -- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>. -- If there is no <tt>Base</tt> object, the request attribute with the given name is -- updated to the given value. overriding procedure Set_Value (Resolver : in out ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Ada.Strings.Unbounded.Unbounded_String; Value : in Util.Beans.Objects.Object); private type ELResolver is new Ada.Finalization.Limited_Controlled and EL.Contexts.ELResolver with record -- The current request. Request : ASF.Requests.Request_Access; -- The current ASF application. Application : ASF.Applications.Main.Application_Access; -- A list of attributes that have been created specifically for this resolver -- and whose scope is only the current resolver. Attributes : aliased Util.Beans.Objects.Maps.Map; Attributes_Access : access Util.Beans.Objects.Maps.Map; end record; -- Initialize the resolver. overriding procedure Initialize (Resolver : in out ELResolver); end ASF.Beans.Resolvers;
----------------------------------------------------------------------- -- asf-beans-resolvers -- Resolver to create and give access to managed beans -- Copyright (C) 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with EL.Contexts; with ASF.Applications.Main; with ASF.Requests; package ASF.Beans.Resolvers is -- ------------------------------ -- Bean Resolver -- ------------------------------ type ELResolver is limited new EL.Contexts.ELResolver with private; -- Initialize the EL resolver to use the application bean factory and the given request. procedure Initialize (Resolver : in out ELResolver; App : in ASF.Applications.Main.Application_Access; Request : in ASF.Requests.Request_Access); -- Resolve the name represented by <tt>Name</tt> according to a base object <tt>Base</tt>. -- The resolver tries to look first in pre-defined objects (params, flash, headers, initParam). -- It then looks in the request and session attributes for the value. If the value was -- not in the request or session, it uses the application bean factory to create the -- new managed bean and adds it to the request or session. overriding function Get_Value (Resolver : in ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Ada.Strings.Unbounded.Unbounded_String) return Util.Beans.Objects.Object; -- Sets the value represented by the <tt>Name</tt> in the base object <tt>Base</tt>. -- If there is no <tt>Base</tt> object, the request attribute with the given name is -- updated to the given value. overriding procedure Set_Value (Resolver : in out ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Ada.Strings.Unbounded.Unbounded_String; Value : in Util.Beans.Objects.Object); private type ELResolver is limited new Ada.Finalization.Limited_Controlled and EL.Contexts.ELResolver with record -- The current request. Request : ASF.Requests.Request_Access; -- The current ASF application. Application : ASF.Applications.Main.Application_Access; -- A list of attributes that have been created specifically for this resolver -- and whose scope is only the current resolver. Attributes : aliased Util.Beans.Objects.Maps.Map; Attributes_Access : access Util.Beans.Objects.Maps.Map; end record; -- Initialize the resolver. overriding procedure Initialize (Resolver : in out ELResolver); end ASF.Beans.Resolvers;
Fix compilation with GNAT 2015: the ELResolver must be explicitly declared as limited
Fix compilation with GNAT 2015: the ELResolver must be explicitly declared as limited
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8af645ce82dd4cc8262a9f42fa453fd64e7a60a8
src/asf-contexts-writer.ads
src/asf-contexts-writer.ads
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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. ----------------------------------------------------------------------- -- The <b>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9aee3fe2dfabd1baf7ab0a62c63955c07d0a0b39
src/asf-views-nodes-jsf.ads
src/asf-views-nodes-jsf.ads
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013, 2014, 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.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Convert Date Time Tag -- ------------------------------ -- The <b>Convert_Date_Time_Tag_Node</b> is created in the facelet tree when -- the <f:converterDateTime> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with private; type Convert_Date_Time_Tag_Node_Access is access all Convert_Date_Time_Tag_Node'Class; -- Create the Converter Tag function Create_Convert_Date_Time_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Convert_Date_Time_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with record Date_Style : Tag_Attribute_Access; Time_Style : Tag_Attribute_Access; Locale : Tag_Attribute_Access; Pattern : Tag_Attribute_Access; Format : Tag_Attribute_Access; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- asf-views-nodes-jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013, 2014, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Convert Date Time Tag -- ------------------------------ -- The <b>Convert_Date_Time_Tag_Node</b> is created in the facelet tree when -- the <f:converterDateTime> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with private; type Convert_Date_Time_Tag_Node_Access is access all Convert_Date_Time_Tag_Node'Class; -- Create the Converter Tag function Create_Convert_Date_Time_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Convert_Date_Time_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Regex Validator Tag -- ------------------------------ -- The <b>Regex_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateRegex> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Regex_Validator_Tag_Node is new Validator_Tag_Node with private; type Regex_Validator_Tag_Node_Access is access all Regex_Validator_Tag_Node'Class; -- Create the Regex_Validator Tag. Verifies that the XML node defines -- the <b>pattern</b> and that it is a valid regular expression. function Create_Regex_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Regex_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with record Date_Style : Tag_Attribute_Access; Time_Style : Tag_Attribute_Access; Locale : Tag_Attribute_Access; Pattern : Tag_Attribute_Access; Format : Tag_Attribute_Access; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Regex_Validator_Tag_Node is new Validator_Tag_Node with record Pattern : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
Declare Regex_Validator_Tag_Node to describe the <f:validateRegex> tag
Declare Regex_Validator_Tag_Node to describe the <f:validateRegex> tag
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ad7e61d52003873d03c742b75762b92df31ac68d
awa/src/awa-services-contexts.adb
awa/src/awa-services-contexts.adb
----------------------------------------------------------------------- -- awa-services -- Services -- Copyright (C) 2011, 2012, 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 Ada.Task_Attributes; with ADO.Databases; with Security.Contexts; package body AWA.Services.Contexts is use type ADO.Databases.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin -- If a master database session was created, use it. if Ctx.Master.Get_Status = ADO.Databases.OPEN then return ADO.Sessions.Session (Ctx.Master); elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Get the attribute registered under the given name in the HTTP session. -- ------------------------------ function Get_Session_Attribute (Ctx : in Service_Context; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Ctx, Name); begin return Util.Beans.Objects.Null_Object; end Get_Session_Attribute; -- ------------------------------ -- Set the attribute registered under the given name in the HTTP session. -- ------------------------------ procedure Set_Session_Attribute (Ctx : in out Service_Context; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Session_Attribute; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Run the process procedure on behalf of the specific user and session. -- This operation changes temporarily the identity of the current user principal and -- executes the <tt>Process</tt> procedure. -- ------------------------------ procedure Run_As (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) is Ctx : Service_Context; Sec : Security.Contexts.Security_Context; Principal : aliased AWA.Users.Principals.Principal := AWA.Users.Principals.Create (User, Session); begin Ctx.Principal := Principal'Unchecked_Access; Sec.Set_Context (Ctx.Application.Get_Security_Manager, Principal'Unchecked_Access); Process; end Run_As; end AWA.Services.Contexts;
----------------------------------------------------------------------- -- awa-services -- Services -- Copyright (C) 2011, 2012, 2013, 2014, 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.Task_Attributes; with Security.Contexts; package body AWA.Services.Contexts is use type ADO.Sessions.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin -- If a master database session was created, use it. if Ctx.Master.Get_Status = ADO.Sessions.OPEN then return ADO.Sessions.Session (Ctx.Master); elsif Ctx.Slave.Get_Status /= ADO.Sessions.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Sessions.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Get the attribute registered under the given name in the HTTP session. -- ------------------------------ function Get_Session_Attribute (Ctx : in Service_Context; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Ctx, Name); begin return Util.Beans.Objects.Null_Object; end Get_Session_Attribute; -- ------------------------------ -- Set the attribute registered under the given name in the HTTP session. -- ------------------------------ procedure Set_Session_Attribute (Ctx : in out Service_Context; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Session_Attribute; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Run the process procedure on behalf of the specific user and session. -- This operation changes temporarily the identity of the current user principal and -- executes the <tt>Process</tt> procedure. -- ------------------------------ procedure Run_As (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) is Ctx : Service_Context; Sec : Security.Contexts.Security_Context; Principal : aliased AWA.Users.Principals.Principal := AWA.Users.Principals.Create (User, Session); begin Ctx.Principal := Principal'Unchecked_Access; Sec.Set_Context (Ctx.Application.Get_Security_Manager, Principal'Unchecked_Access); Process; end Run_As; end AWA.Services.Contexts;
Update to use the ADO.Sessions package for the Connection_Status type
Update to use the ADO.Sessions package for the Connection_Status type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2d6c653cf27d4dbbfcc80069734101b395b74884
src/el-contexts-default.adb
src/el-contexts-default.adb
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Variables; with EL.Variables.Default; package body EL.Contexts.Default is -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the VariableMapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.VariableMapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin Context.Function_Mapper := Mapper.all'Unchecked_Access; end Set_Function_Mapper; -- ------------------------------ -- Set the VariableMapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.VariableMapper'Class) is use EL.Variables; begin if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access EL.Beans.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value)); end Set_Variable; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); R : Object; begin if Base /= null then return Base.Get_Value (To_String (Name)); end if; declare Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then return Bean_Maps.Element (Pos); end if; end; return R; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in Default_ELResolver; Context : in ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access EL.Beans.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Bean_Maps.Include (Resolver.Map, Name, Value); end Register; end EL.Contexts.Default;
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Variables; with EL.Variables.Default; package body EL.Contexts.Default is -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the VariableMapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.VariableMapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the VariableMapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.VariableMapper'Class) is use EL.Variables; begin if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access EL.Beans.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value)); end Set_Variable; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); R : Object; begin if Base /= null then return Base.Get_Value (To_String (Name)); end if; declare Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then return Bean_Maps.Element (Pos); end if; end; return R; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in Default_ELResolver; Context : in ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access EL.Beans.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Bean_Maps.Include (Resolver.Map, Name, Value); end Register; end EL.Contexts.Default;
Fix Set_Variable_Mapper to allow to set a null function mapper.
Fix Set_Variable_Mapper to allow to set a null function mapper.
Ada
apache-2.0
Letractively/ada-el
a390437e05b1c55c971e48547b3b3dcd75cb2391
src/el-contexts-default.adb
src/el-contexts-default.adb
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Variables; with EL.Variables.Default; package body EL.Contexts.Default is -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the VariableMapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.VariableMapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the VariableMapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.VariableMapper'Class) is use EL.Variables; begin if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access EL.Beans.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value)); end Set_Variable; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); R : Object; begin if Base /= null then return Base.Get_Value (To_String (Name)); end if; declare Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then return Bean_Maps.Element (Pos); end if; end; return R; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in Default_ELResolver; Context : in ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access EL.Beans.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Bean_Maps.Include (Resolver.Map, Name, Value); end Register; end EL.Contexts.Default;
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Variables.Default; package body EL.Contexts.Default is -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the VariableMapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.VariableMapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the VariableMapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.VariableMapper'Class) is use EL.Variables; begin if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access EL.Beans.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value)); end Set_Variable; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); R : Object; begin if Base /= null then return Base.Get_Value (To_String (Name)); end if; declare Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then return Bean_Maps.Element (Pos); end if; end; return R; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in Default_ELResolver; Context : in ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access EL.Beans.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Bean_Maps.Include (Resolver.Map, Name, Value); end Register; end EL.Contexts.Default;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-el
4daa04283225169e287578830a4d663591d98ec4
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Inviter : AWA.Users.Models.User_Ref; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Member_Bean is new AWA.Workspaces.Models.Member_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Member_Bean_Access is access all Member_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_Bean bean instance. function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Inviter : AWA.Users.Models.User_Ref; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Invitation_Bean bean instance. function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Declare the Member_Bean type with its operations
Declare the Member_Bean type with its operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9128585993f2ece675ecb5f16810520bc0cbb9e1
ada/reader.adb
ada/reader.adb
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Exceptions; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Smart_Pointers; with Types.Vector; with Types.Hash_Map; package body Reader is use Types; package ACL renames Ada.Characters.Latin_1; type Lexemes is (Ignored_Tok, Start_List_Tok, Start_Vector_Tok, Start_Hash_Tok, Meta_Tok, Deref_Tok, Quote_Tok, Quasi_Quote_Tok, Splice_Unq_Tok, Unquote_Tok, Int_Tok, Float_Tok, Str_Tok, Sym_Tok); type Token (ID : Lexemes := Ignored_Tok) is record case ID is when Int_Tok => Int_Val : Mal_Integer; when Float_Tok => Float_Val : Mal_Float; when Str_Tok | Sym_Tok => Start_Char, Stop_Char : Natural; when others => null; end case; end record; Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (ACL.HT & ACL.LF & ACL.CR & ACL.Space & ACL.Comma); -- [^\s\[\]{}('"`,;)] Terminator_Syms : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Lisp_Whitespace, Ada.Strings.Maps.To_Set ("[]{}('""`,;)")); -- The unterminated string error String_Error : exception; function Convert_String (S : String) return String is use Ada.Strings.Unbounded; Res : Unbounded_String; I : Positive; Str_Last : Natural; begin Str_Last := S'Last; I := S'First; while I <= Str_Last loop if S (I) = '\' then if I+1 > Str_Last then Append (Res, S (I)); I := I + 1; elsif S (I+1) = 'n' then Append (Res, Ada.Characters.Latin_1.LF); I := I + 2; elsif S (I+1) = '"' then Append (Res, S (I+1)); I := I + 2; elsif S (I+1) = '\' then Append (Res, S (I+1)); I := I + 2; else Append (Res, S (I)); I := I + 1; end if; else Append (Res, S (I)); I := I + 1; end if; end loop; return To_String (Res); end Convert_String; Str_Len : Natural := 0; Saved_Line : Ada.Strings.Unbounded.Unbounded_String; Char_To_Read : Natural := 1; function Get_Token return Token is Res : Token; I, J : Natural; use Ada.Strings.Unbounded; begin <<Tail_Call_Opt>> -- Skip over whitespace... I := Char_To_Read; while I <= Str_Len and then Ada.Strings.Maps.Is_In (Element (Saved_Line, I), Lisp_Whitespace) loop I := I + 1; end loop; -- Filter out lines consisting of only whitespace if I > Str_Len then return (ID => Ignored_Tok); end if; J := I; case Element (Saved_Line, J) is when ''' => Res := (ID => Quote_Tok); Char_To_Read := J+1; when '`' => Res := (ID => Quasi_Quote_Tok); Char_To_Read := J+1; when '~' => -- Tilde if J+1 <= Str_Len and then Element (Saved_Line, J+1) = '@' then Res := (ID => Splice_Unq_Tok); Char_To_Read := J+2; else -- Just a Tilde Res := (ID => Unquote_Tok); Char_To_Read := J+1; end if; when '(' => Res := (ID => Start_List_Tok); Char_To_Read := J+1; when '[' => Res := (ID => Start_Vector_Tok); Char_To_Read := J+1; when '{' => Res := (ID => Start_Hash_Tok); Char_To_Read := J+1; when '^' => Res := (ID => Meta_Tok); Char_To_Read := J+1; when '@' => Res := (ID => Deref_Tok); Char_To_Read := J+1; when ']' | '}' | ')' => Res := (ID => Sym_Tok, Start_Char => J, Stop_Char => J); Char_To_Read := J+1; when '"' => -- a string -- Skip over " J := J + 1; while J <= Str_Len and then (Element (Saved_Line, J) /= '"' or else Element (Saved_Line, J-1) = '\') loop J := J + 1; end loop; -- So we either ran out of string.. if J > Str_Len then raise String_Error; end if; -- or we reached an unescaped " Res := (ID => Str_Tok, Start_Char => I, Stop_Char => J); Char_To_Read := J + 1; when ';' => -- a comment -- Read to the end of the line or until -- the saved_line string is exhausted. -- NB if we reach the end we don't care -- what the last char was. while J < Str_Len and Element (Saved_Line, J) /= ACL.LF loop J := J + 1; end loop; if J = Str_Len then Res := (ID => Ignored_Tok); else Char_To_Read := J + 1; -- was: Res := Get_Token; goto Tail_Call_Opt; end if; when others => -- an atom while J <= Str_Len and then not Ada.Strings.Maps.Is_In (Element (Saved_Line, J), Terminator_Syms) loop J := J + 1; end loop; -- Either we ran out of string or -- the one at J was the start of a new token Char_To_Read := J; J := J - 1; declare Dots : Natural; All_Digits : Boolean; begin -- check if all digits or . Dots := 0; All_Digits := True; for K in I .. J loop if Element (Saved_Line, K) = '.' then Dots := Dots + 1; elsif not (Element (Saved_Line, K) in '0' .. '9') then All_Digits := False; exit; end if; end loop; if All_Digits then if Dots = 0 then Res := (ID => Int_Tok, Int_Val => Mal_Integer'Value (Slice (Saved_Line, I, J))); elsif Dots = 1 then Res := (ID => Float_Tok, Float_Val => Mal_Float'Value (Slice (Saved_Line, I, J))); else Res := (ID => Sym_Tok, Start_Char => I, Stop_Char => J); end if; else Res := (ID => Sym_Tok, Start_Char => I, Stop_Char => J); end if; end; end case; return Res; end Get_Token; function Read_List (LT : Types.List_Types) return Types.Mal_Handle is MTA : Mal_Handle; begin MTA := Read_Form; declare List_SP : Mal_Handle; List_P : List_Class_Ptr; Close : String (1..1) := (1 => Types.Closing (LT)); begin case LT is when List_List => List_SP := New_List_Mal_Type (List_Type => LT); when Vector_List => List_SP := Vector.New_Vector_Mal_Type; when Hashed_List => List_SP := Hash_Map.New_Hash_Map_Mal_Type; end case; -- Need to append to a variable so... List_P := Deref_List_Class (List_SP); loop if Is_Null (MTA) then return New_Error_Mal_Type (Str => "expected '" & Close & "'"); end if; exit when Deref (MTA).Sym_Type = Sym and then Symbol_Mal_Type (Deref (MTA).all).Get_Sym = Close; Append (List_P.all, MTA); MTA := Read_Form; end loop; return List_SP; end; end Read_List; function Read_Form return Types.Mal_Handle is Tok : Token; MTS : Mal_Handle; use Ada.Strings.Unbounded; begin Tok := Get_Token; case Tok.ID is when Ignored_Tok => return Smart_Pointers.Null_Smart_Pointer; when Int_Tok => return New_Int_Mal_Type (Tok.Int_Val); when Float_Tok => return New_Float_Mal_Type (Tok.Float_Val); when Start_List_Tok => return Read_List (List_List); when Start_Vector_Tok => return Read_List (Vector_List); when Start_Hash_Tok => return Read_List (Hashed_List); when Meta_Tok => declare Meta, Obj : Mal_Handle; begin Meta := Read_Form; Obj := Read_Form; return Make_New_List ((1 => New_Symbol_Mal_Type ("with-meta"), 2 => Obj, 3 => Meta)); end; when Deref_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("deref"), 2 => Read_Form)); when Quote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("quote"), 2 => Read_Form)); when Quasi_Quote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("quasiquote"), 2 => Read_Form)); when Splice_Unq_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("splice-unquote"), 2 => Read_Form)); when Unquote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("unquote"), 2 => Read_Form)); when Str_Tok => return New_String_Mal_Type (Convert_String (Slice (Saved_Line, Tok.Start_Char, Tok.Stop_Char))); when Sym_Tok => return New_Symbol_Mal_Type (Slice (Saved_Line, Tok.Start_Char, Tok.Stop_Char)); end case; end Read_Form; procedure Lex_Init (S : String) is begin Str_Len := S'Length; Saved_Line := Ada.Strings.Unbounded.To_Unbounded_String (S); Char_To_Read := 1; end Lex_Init; function Read_Str (S : String) return Types.Mal_Handle is I, Str_Len : Natural := S'Length; begin Lex_Init (S); return Read_Form; exception when String_Error => return New_Error_Mal_Type (Str => "expected '""'"); end Read_Str; end Reader;
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Exceptions; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Smart_Pointers; with Types.Vector; with Types.Hash_Map; package body Reader is use Types; package ACL renames Ada.Characters.Latin_1; type Lexemes is (Ignored_Tok, Start_List_Tok, Start_Vector_Tok, Start_Hash_Tok, Meta_Tok, Deref_Tok, Quote_Tok, Quasi_Quote_Tok, Splice_Unq_Tok, Unquote_Tok, Int_Tok, Float_Tok, Str_Tok, Sym_Tok); type Token (ID : Lexemes := Ignored_Tok) is record case ID is when Int_Tok => Int_Val : Mal_Integer; when Float_Tok => Float_Val : Mal_Float; when Str_Tok | Sym_Tok => Start_Char, Stop_Char : Natural; when others => null; end case; end record; Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (ACL.HT & ACL.LF & ACL.CR & ACL.Space & ACL.Comma); -- [^\s\[\]{}('"`,;)] Terminator_Syms : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Lisp_Whitespace, Ada.Strings.Maps.To_Set ("[]{}('""`,;)")); -- The unterminated string error String_Error : exception; function Convert_String (S : String) return String is use Ada.Strings.Unbounded; Res : Unbounded_String; I : Positive; Str_Last : Natural; begin Str_Last := S'Last; I := S'First; while I <= Str_Last loop if S (I) = '\' then if I+1 > Str_Last then Append (Res, S (I)); I := I + 1; elsif S (I+1) = 'n' then Append (Res, Ada.Characters.Latin_1.LF); I := I + 2; elsif S (I+1) = '"' then Append (Res, S (I+1)); I := I + 2; elsif S (I+1) = '\' then Append (Res, S (I+1)); I := I + 2; else Append (Res, S (I)); I := I + 1; end if; else Append (Res, S (I)); I := I + 1; end if; end loop; return To_String (Res); end Convert_String; Str_Len : Natural := 0; Saved_Line : Ada.Strings.Unbounded.Unbounded_String; Char_To_Read : Natural := 1; function Get_Token return Token is Res : Token; I, J : Natural; use Ada.Strings.Unbounded; begin <<Tail_Call_Opt>> -- Skip over whitespace... I := Char_To_Read; while I <= Str_Len and then Ada.Strings.Maps.Is_In (Element (Saved_Line, I), Lisp_Whitespace) loop I := I + 1; end loop; -- Filter out lines consisting of only whitespace if I > Str_Len then return (ID => Ignored_Tok); end if; J := I; case Element (Saved_Line, J) is when ''' => Res := (ID => Quote_Tok); Char_To_Read := J+1; when '`' => Res := (ID => Quasi_Quote_Tok); Char_To_Read := J+1; when '~' => -- Tilde if J+1 <= Str_Len and then Element (Saved_Line, J+1) = '@' then Res := (ID => Splice_Unq_Tok); Char_To_Read := J+2; else -- Just a Tilde Res := (ID => Unquote_Tok); Char_To_Read := J+1; end if; when '(' => Res := (ID => Start_List_Tok); Char_To_Read := J+1; when '[' => Res := (ID => Start_Vector_Tok); Char_To_Read := J+1; when '{' => Res := (ID => Start_Hash_Tok); Char_To_Read := J+1; when '^' => Res := (ID => Meta_Tok); Char_To_Read := J+1; when '@' => Res := (ID => Deref_Tok); Char_To_Read := J+1; when ']' | '}' | ')' => Res := (ID => Sym_Tok, Start_Char => J, Stop_Char => J); Char_To_Read := J+1; when '"' => -- a string -- Skip over " J := J + 1; while J <= Str_Len and then (Element (Saved_Line, J) /= '"' or else Element (Saved_Line, J-1) = '\') loop J := J + 1; end loop; -- So we either ran out of string.. if J > Str_Len then raise String_Error; end if; -- or we reached an unescaped " Res := (ID => Str_Tok, Start_Char => I, Stop_Char => J); Char_To_Read := J + 1; when ';' => -- a comment -- Read to the end of the line or until -- the saved_line string is exhausted. -- NB if we reach the end we don't care -- what the last char was. while J < Str_Len and Element (Saved_Line, J) /= ACL.LF loop J := J + 1; end loop; if J = Str_Len then Res := (ID => Ignored_Tok); else Char_To_Read := J + 1; -- was: Res := Get_Token; goto Tail_Call_Opt; end if; when others => -- an atom while J <= Str_Len and then not Ada.Strings.Maps.Is_In (Element (Saved_Line, J), Terminator_Syms) loop J := J + 1; end loop; -- Either we ran out of string or -- the one at J was the start of a new token Char_To_Read := J; J := J - 1; declare Dots : Natural; All_Digits : Boolean; begin -- check if all digits or . Dots := 0; All_Digits := True; for K in I .. J loop if Element (Saved_Line, K) = '.' then Dots := Dots + 1; elsif not (Element (Saved_Line, K) in '0' .. '9') then All_Digits := False; exit; end if; end loop; if All_Digits then if Dots = 0 then Res := (ID => Int_Tok, Int_Val => Mal_Integer'Value (Slice (Saved_Line, I, J))); elsif Dots = 1 then Res := (ID => Float_Tok, Float_Val => Mal_Float'Value (Slice (Saved_Line, I, J))); else Res := (ID => Sym_Tok, Start_Char => I, Stop_Char => J); end if; else Res := (ID => Sym_Tok, Start_Char => I, Stop_Char => J); end if; end; end case; return Res; end Get_Token; function Read_List (LT : Types.List_Types) return Types.Mal_Handle is MTA : Mal_Handle; begin MTA := Read_Form; declare List_SP : Mal_Handle; List_P : List_Class_Ptr; Close : String (1..1) := (1 => Types.Closing (LT)); begin case LT is when List_List => List_SP := New_List_Mal_Type (List_Type => LT); when Vector_List => List_SP := Vector.New_Vector_Mal_Type; when Hashed_List => List_SP := Hash_Map.New_Hash_Map_Mal_Type; end case; -- Need to append to a variable so... List_P := Deref_List_Class (List_SP); loop if Is_Null (MTA) then return New_Error_Mal_Type (Str => "expected '" & Close & "'"); end if; exit when Deref (MTA).Sym_Type = Sym and then Symbol_Mal_Type (Deref (MTA).all).Get_Sym = Close; Append (List_P.all, MTA); MTA := Read_Form; end loop; return List_SP; end; end Read_List; function Read_Form return Types.Mal_Handle is Tok : Token; MTS : Mal_Handle; use Ada.Strings.Unbounded; begin Tok := Get_Token; case Tok.ID is when Ignored_Tok => return Smart_Pointers.Null_Smart_Pointer; when Int_Tok => return New_Int_Mal_Type (Tok.Int_Val); when Float_Tok => return New_Float_Mal_Type (Tok.Float_Val); when Start_List_Tok => return Read_List (List_List); when Start_Vector_Tok => return Read_List (Vector_List); when Start_Hash_Tok => return Read_List (Hashed_List); when Meta_Tok => declare Meta, Obj : Mal_Handle; begin Meta := Read_Form; Obj := Read_Form; return Make_New_List ((1 => New_Symbol_Mal_Type ("with-meta"), 2 => Obj, 3 => Meta)); end; when Deref_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("deref"), 2 => Read_Form)); when Quote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("quote"), 2 => Read_Form)); when Quasi_Quote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("quasiquote"), 2 => Read_Form)); when Splice_Unq_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("splice-unquote"), 2 => Read_Form)); when Unquote_Tok => return Make_New_List ((1 => New_Symbol_Mal_Type ("unquote"), 2 => Read_Form)); when Str_Tok => return New_String_Mal_Type (Convert_String (Slice (Saved_Line, Tok.Start_Char, Tok.Stop_Char))); when Sym_Tok => -- Mal interpreter is required to know about true, false and nil. declare S : String := Slice (Saved_Line, Tok.Start_Char, Tok.Stop_Char); begin if S = "true" then return New_Bool_Mal_Type (True); elsif S = "false" then return New_Bool_Mal_Type (False); else return New_Symbol_Mal_Type (S); end if; end; end case; end Read_Form; procedure Lex_Init (S : String) is begin Str_Len := S'Length; Saved_Line := Ada.Strings.Unbounded.To_Unbounded_String (S); Char_To_Read := 1; end Lex_Init; function Read_Str (S : String) return Types.Mal_Handle is I, Str_Len : Natural := S'Length; begin Lex_Init (S); return Read_Form; exception when String_Error => return New_Error_Mal_Type (Str => "expected '""'"); end Read_Str; end Reader;
build in knowledge about true and false into reader
Ada: build in knowledge about true and false into reader
Ada
mpl-2.0
alantsev/mal,foresterre/mal,mpwillson/mal,jwalsh/mal,0gajun/mal,jwalsh/mal,jwalsh/mal,SawyerHood/mal,hterkelsen/mal,SawyerHood/mal,hterkelsen/mal,DomBlack/mal,mpwillson/mal,0gajun/mal,SawyerHood/mal,jwalsh/mal,0gajun/mal,foresterre/mal,0gajun/mal,DomBlack/mal,SawyerHood/mal,SawyerHood/mal,DomBlack/mal,hterkelsen/mal,mpwillson/mal,alantsev/mal,foresterre/mal,alantsev/mal,0gajun/mal,DomBlack/mal,jwalsh/mal,SawyerHood/mal,hterkelsen/mal,foresterre/mal,hterkelsen/mal,0gajun/mal,jwalsh/mal,mpwillson/mal,foresterre/mal,foresterre/mal,jwalsh/mal,alantsev/mal,jwalsh/mal,mpwillson/mal,mpwillson/mal,foresterre/mal,DomBlack/mal,SawyerHood/mal,0gajun/mal,SawyerHood/mal,SawyerHood/mal,DomBlack/mal,hterkelsen/mal,hterkelsen/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,alantsev/mal,hterkelsen/mal,DomBlack/mal,foresterre/mal,alantsev/mal,hterkelsen/mal,alantsev/mal,foresterre/mal,mpwillson/mal,mpwillson/mal,foresterre/mal,mpwillson/mal,hterkelsen/mal,0gajun/mal,joncol/mal,jwalsh/mal,alantsev/mal,alantsev/mal,alantsev/mal,foresterre/mal,joncol/mal,DomBlack/mal,foresterre/mal,hterkelsen/mal,mpwillson/mal,alantsev/mal,SawyerHood/mal,alantsev/mal,jwalsh/mal,foresterre/mal,0gajun/mal,jwalsh/mal,jwalsh/mal,SawyerHood/mal,DomBlack/mal,SawyerHood/mal,DomBlack/mal,mpwillson/mal,hterkelsen/mal,SawyerHood/mal,alantsev/mal,jwalsh/mal,0gajun/mal,SawyerHood/mal,0gajun/mal,0gajun/mal,0gajun/mal,SawyerHood/mal,DomBlack/mal,foresterre/mal,DomBlack/mal,jwalsh/mal,joncol/mal,alantsev/mal,jwalsh/mal,SawyerHood/mal,SawyerHood/mal,0gajun/mal,0gajun/mal,0gajun/mal,DomBlack/mal,DomBlack/mal,hterkelsen/mal,hterkelsen/mal,jwalsh/mal,hterkelsen/mal,DomBlack/mal,mpwillson/mal,0gajun/mal,0gajun/mal,jwalsh/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,foresterre/mal,hterkelsen/mal,DomBlack/mal,mpwillson/mal,alantsev/mal,mpwillson/mal,SawyerHood/mal,hterkelsen/mal,hterkelsen/mal,foresterre/mal,DomBlack/mal,alantsev/mal,foresterre/mal,hterkelsen/mal,alantsev/mal
641027857937574e1b90b116cbc28f03b6ec6170
awa/plugins/awa-counters/src/awa-counters-beans.ads
awa/plugins/awa-counters/src/awa-counters-beans.ads
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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.Unbounded; with ADO.Objects; with ADO.Schemas; with Util.Beans.Objects; with Util.Beans.Basic; with AWA.Counters.Modules; with AWA.Counters.Models; -- == Counter Bean == -- The <b>Counter_Bean</b> allows to represent a counter associated with some database -- entity and allows its control by the <awa:counter> component. -- package AWA.Counters.Beans is type Counter_Bean (Of_Type : ADO.Objects.Object_Key_Type; Of_Class : ADO.Schemas.Class_Mapping_Access) is new Util.Beans.Basic.Readonly_Bean with record Counter : Counter_Index_Type; Value : Integer := -1; Object : ADO.Objects.Object_Key (Of_Type, Of_Class); end record; type Counter_Bean_Access is access all Counter_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object; type Counter_Stat_Bean is new AWA.Counters.Models.Stat_List_Bean with record Module : AWA.Counters.Modules.Counter_Module_Access; Stats : aliased AWA.Counters.Models.Stat_Info_List_Bean; Stats_Bean : AWA.Counters.Models.Stat_Info_List_Bean_Access; end record; type Counter_Stat_Bean_Access is access all Counter_Stat_Bean'Class; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Counters.Beans;
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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.Unbounded; with ADO.Objects; with ADO.Schemas; with ADO.Queries; with Util.Beans.Objects; with Util.Beans.Basic; with AWA.Counters.Modules; with AWA.Counters.Models; -- == Counter Bean == -- The <b>Counter_Bean</b> allows to represent a counter associated with some database -- entity and allows its control by the <awa:counter> component. -- package AWA.Counters.Beans is type Counter_Bean (Of_Type : ADO.Objects.Object_Key_Type; Of_Class : ADO.Schemas.Class_Mapping_Access) is new Util.Beans.Basic.Readonly_Bean with record Counter : Counter_Index_Type; Value : Integer := -1; Object : ADO.Objects.Object_Key (Of_Type, Of_Class); end record; type Counter_Bean_Access is access all Counter_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object; type Counter_Stat_Bean is new AWA.Counters.Models.Stat_List_Bean with record Module : AWA.Counters.Modules.Counter_Module_Access; Stats : aliased AWA.Counters.Models.Stat_Info_List_Bean; Stats_Bean : AWA.Counters.Models.Stat_Info_List_Bean_Access; end record; type Counter_Stat_Bean_Access is access all Counter_Stat_Bean'Class; -- Get the query definition to collect the counter statistics. function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Counters.Beans;
Declare the Get_Query operation
Declare the Get_Query operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ecab6350f29c0f37153ec52455ac791fd39abac5
src/sys/streams/util-streams-texts.adb
src/sys/streams/util-streams-texts.adb
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Char : in Character) is Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1) := (1 => Ada.Streams.Stream_Element (Character'Pos (Char))); begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; Buf : Ada.Streams.Stream_Element_Array (1 .. 4); begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Buf (1) := Ada.Streams.Stream_Element (Val); Stream.Write (Buf (1 .. 1)); elsif Val <= 16#07FF# then Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6)); Buf (2) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 2)); elsif Val <= 16#0FFFF# then Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (3) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 3)); else Val := Val and 16#1FFFFF#; Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18)); Val := Val and 16#3FFFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (4) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 4)); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in String) is Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last)); for Buf'Address use Item'Address; begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_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 Print_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 an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 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 Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_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 (Item => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_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_Wide (C); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
Remove Write and Write_Wide procedures which are now provided by a parent package
Remove Write and Write_Wide procedures which are now provided by a parent package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c609dbba3e7e0e5e3b882675c78b4cd7f0327afc
src/cbap.ads
src/cbap.ads
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ with Ada.Containers.Indefinite_Vectors; ------------------------------------------------------------------------------ -- Small and simple callback based library for processing program arguments -- ------------------------------------------------------------------------------ --------------------------------------------------------------------------- -- U S A G E -- --------------------------------------------------------------------------- -- First register all callbacks you are interested in, then call -- Process_Arguments. -- -- NOTE: "=" sign can't be part of argument name for registered callback. -- -- Only one callback can be registered per argument, otherwise -- Constraint_Error is propagated. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- Leading single hyphen and double hyphen are stripped (if present) when -- processing arguments that are placed before first "--" argument, -- so ie. "--help", "-help" and "help" are functionally -- equivalent, treated as if "help" was actually passed in all 3 cases. -- (you should register callback just for "help", if you register it for -- "--help" then actually passed argument would have to be "----help" in order -- for it to trigger said callback) -- -- In addition if you registered callback as case insensitive, then -- (using above example) "Help", "HELP", "help" and "HeLp" all would result in -- call to said callback. -- -- If Argument_Type is Variable then callback will receive part of argument -- that is after "=" sign. (ie. "OS=Linux" argument would result in callback -- receiving only "Linux" as its argument), otherwise actual argument will be -- passed. -- -- For Variable, case insensitive callbacks simple rule applies: -- only variable name is case insensitive, with actual value (when passed to -- program) being unchanged. -- -- All arguments with no associated callback are added to Unknown_Arguments -- vector as long as they appear before first "--" argument. -- -- All arguments after first "--" (standalone double hyphen) are added to -- Input_Argument vector (this includes another "--"), w/o any kind of -- hyphen stripping being performed on them. -- -- NOTE: No care is taken to ensure that all Input_Arguments -- (or Unknown_Arguments) are unique. --------------------------------------------------------------------------- package CBAP is --------------------------------------------------------------------------- -- Yes, I do realize this is actually vector... package Argument_Lists is new Ada.Containers.Indefinite_Vectors (Positive, String); -- List of all arguments (before first "--" argument) for which callbacks -- where not registered. Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- List of all arguments after first "--" argument. Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- Argument_Types decides if argument is just a simple value, or a variable -- with value assigned to it (difference between "--val" and "--var=val") type Argument_Types is (Value, Variable); -- Argument is useful mostly for Variable type of arguments. type Callbacks is not null access procedure (Argument: in String); --------------------------------------------------------------------------- -- Register callbacks for processing arguments. -- @Callback : Action to be performed in case appropriate argument is -- detected. -- @Called_On : Argument for which callback is to be performed. -- @Argument_Type : {Value, Variable}. Value is simple argument that needs no -- additional parsing. Variable is argument of "Arg_Name=Some_Val" form. -- When callback is triggered, Value is passed to callback as input, in -- case of Variable it is content of argument after first "=" that is -- passed to callback. -- @Case_Sensitive: Whether or not case is significant. When False all forms -- of argument are treated as if written in lower case. procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ); -- Raised if Called_On contains "=". Incorrect_Called_On: exception; --------------------------------------------------------------------------- -- Parse arguments supplied to program, calling callbacks when argument with -- associated callback is detected. -- NOTE: Process_Arguments will call callbacks however many times argument -- with associated callback is called. So if you have callback for "help", -- then ./program help help help -- will result in 3 calls to said callback. procedure Process_Arguments; --------------------------------------------------------------------------- end CBAP;
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC License (see COPYING file) -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ with Ada.Containers.Indefinite_Vectors; ------------------------------------------------------------------------------ -- Small and simple callback based library for processing program arguments -- ------------------------------------------------------------------------------ --------------------------------------------------------------------------- -- U S A G E -- --------------------------------------------------------------------------- -- First register all callbacks you are interested in, then call -- Process_Arguments. -- -- NOTE: "=" sign can't be part of argument name for registered callback. -- -- Only one callback can be registered per argument, otherwise -- Constraint_Error is propagated. --------------------------------------------------------------------------- --------------------------------------------------------------------------- -- Leading single hyphen and double hyphen are stripped (if present) when -- processing arguments that are placed before first "--" argument, -- so ie. "--help", "-help" and "help" are functionally -- equivalent, treated as if "help" was actually passed in all 3 cases. -- (you should register callback just for "help", if you register it for -- "--help" then actually passed argument would have to be "----help" in order -- for it to trigger said callback) -- -- In addition if you registered callback as case insensitive, then -- (using above example) "Help", "HELP", "help" and "HeLp" all would result in -- call to said callback. -- -- If Argument_Type is Variable then callback will receive part of argument -- that is after "=" sign. (ie. "OS=Linux" argument would result in callback -- receiving only "Linux" as its argument), otherwise actual argument will be -- passed. -- -- For Variable, case insensitive callbacks simple rule applies: -- only variable name is case insensitive, with actual value (when passed to -- program) being unchanged. -- -- If argument for which callback is registered is passed few times -- (ie. ./program help help help) then callback is triggered however many -- times said argument is detected. -- -- All arguments with no associated callback are added to Unknown_Arguments -- vector as long as they appear before first "--" argument. -- -- All arguments after first "--" (standalone double hyphen) are added to -- Input_Argument vector (this includes another "--"), w/o any kind of -- hyphen stripping being performed on them. -- -- NOTE: No care is taken to ensure that all Input_Arguments -- (or Unknown_Arguments) are unique. --------------------------------------------------------------------------- package CBAP is --------------------------------------------------------------------------- -- Yes, I do realize this is actually vector... package Argument_Lists is new Ada.Containers.Indefinite_Vectors (Positive, String); -- List of all arguments (before first "--" argument) for which callbacks -- where not registered. Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- List of all arguments after first "--" argument. Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector; -- Argument_Types decides if argument is just a simple value, or a variable -- with value assigned to it (difference between "--val" and "--var=val") type Argument_Types is (Value, Variable); -- Argument is useful mostly for Variable type of arguments. type Callbacks is not null access procedure (Argument: in String); --------------------------------------------------------------------------- -- Register callbacks for processing arguments. -- @Callback : Action to be performed in case appropriate argument is -- detected. -- @Called_On : Argument for which callback is to be performed. -- @Argument_Type : {Value, Variable}. Value is simple argument that needs no -- additional parsing. Variable is argument of "Arg_Name=Some_Val" form. -- When callback is triggered, Value is passed to callback as input, in -- case of Variable it is content of argument after first "=" that is -- passed to callback. -- @Case_Sensitive: Whether or not case is significant. When False all forms -- of argument are treated as if written in lower case. procedure Register ( Callback : in Callbacks; Called_On : in String; Argument_Type : in Argument_Types := Value; Case_Sensitive: in Boolean := True ); -- Raised if Called_On contains "=". Incorrect_Called_On: exception; --------------------------------------------------------------------------- -- Parse arguments supplied to program, calling callbacks when argument with -- associated callback is detected. -- NOTE: Process_Arguments will call callbacks however many times argument -- with associated callback is called. So if you have callback for "help", -- then ./program help help help -- will result in 3 calls to said callback. procedure Process_Arguments; --------------------------------------------------------------------------- end CBAP;
Update comments.
Update comments. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/cbap
8700b6444372f9d77da3eeedbe8d05076555f945
regtests/util-commands-tests.adb
regtests/util-commands-tests.adb
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration); -- Write the help associated with the command. procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); D.Usage (Args); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration); -- Write the help associated with the command. procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); D.Usage (Args); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
Fix the Test_Usage unit test
Fix the Test_Usage unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util